2014-12-22 67 views
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()静态方法,但无济于事。任何帮助都感激不尽。!

干杯。

更新:上面的代码实际上按预期工作,我得到的错误与此处的任何内容完全无关。

回答

0

对于我来说,在Matlab R2013a,foo = Foo(input)已经是一个错误:Matlab的期望构造被称为Foo,不constructor - 和一个输入参数是一个太多的默认构造函数。如果我将您的方法constructor重命名为Foo,那么它的工作原理和我得到的result等于4.5按预期。

+0

糟糕!这是我在这里粘贴的程序中的一个错字(我的原稿太长,无法在此处显示)。我已经相应地改变了它。 其实,我的程序中的错误是相当愚蠢的。这是一个图像处理问题,我试图使用c + +语法;但MATLAB给它一个奇怪的错误。不管怎样,谢谢。! – scap3y