簡體   English   中英

如何在MATLAB中訪問類變量?

[英]How to access class variables in MATLAB?

我想訪問在同一類的函數中的類中聲明的變量。 例如,在C ++中,代碼看起來像

// 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()作為靜態方法,但無濟於事。 任何幫助都感激不盡。!

干杯。!

更新:上面的代碼實際上按預期方式工作,並且我得到的錯誤與此處的所有內容完全無關。

對我而言,在Matlab R2013a中, foo = Foo(input)已經是一個錯誤:Matlab希望將構造函數稱為Foo ,而不是constructor -並且對於默認構造函數而言,一個輸入參數太多了。 如果我將您的方法constructor重命名為Foo則它可以正常工作,並且得到的result等於預期的4.5

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM