0
我想訪問同一個類中的函數中的類中聲明的變量。例如,在C++中,代碼看起來像:如何訪問MATLAB中的類變量?
// Header
class Foo
{
public:
Foo(int input);
~Foo();
void bar();
int a, b;
}
// Implementation
Foo::Foo(int input)
{
a = input;
}
Foo::~Foo()
{
}
void Foo::bar()
{
b = a/2;
}
// Usage
#include <Foo.h>
int main()
{
int input = 6;
Foo test_class(input);
// Access class variable
std::cout << test_class.b << std::endl;
return EXIT_SUCCESS;
}
我很困惑如何在MATLAB中獲得相同的功能。到目前爲止,我已經做了:
% Class 'm' file
classdef Foo
properties
a;
b;
output;
end
methods
% Class constructor
function obj = Foo(input)
obj.a = input;
obj.b = obj.a/2;
end
% Another function where I want access to 'b'
function output = bar(obj)
output = (obj.b + obj.a)/2;
end
end
end
% Usage
input = 6;
foo = Foo(input);
result = foo.bar(); %MATLAB complains here
我也試圖把bar()
爲靜態方法,但無濟於事。任何幫助都感激不盡。!
乾杯。
更新:上面的代碼實際上按預期工作,我得到的錯誤與此處的任何內容完全無關。
糟糕!這是我在這裏粘貼的程序中的一個錯字(我的原稿太長,無法在此處顯示)。我已經相應地改變了它。 其實,我的程序中的錯誤是相當愚蠢的。這是一個圖像處理問題,我試圖使用c + +語法;但MATLAB給它一個奇怪的錯誤。不管怎樣,謝謝。! – scap3y