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