调用方法时,类实例变量不会保留更改

时间:2016-08-23 14:36:37

标签: matlab oop cell-array private-methods object-properties

我在MATLAB中创建了一个类:

classdef Compiler
%UNTITLED2 Summary of this class goes here
%   Detailed explanation goes here

properties(Access = public)
    in=''       %a line of string of MATLAB code
    out={}      %several lines of string(cell array) of Babbage Code
end

methods(Access = private)
    %compile(compiler);
    expression(compiler); 
    term(compiler);
end

methods(Access = public)
    function compiler = Compiler(str) 
        compiler.in = str;
        expression(compiler);
        compiler.out
    end
end

我的表达功能为:

function expression(compiler)
%Compile(Parse and Generate Babbage code)one line of MATLAB code

   term(compiler);         
end

term功能为:

function term(compiler)
    % Read Number/Variable terms
    num = regexp(compiler.in, '[0-9]+','match');
    len = length(compiler.out);
    compiler.out(len+1,:) = {['Number ' num{1} ' in V0 in Store']}; 
    compiler.out(len+2,:) = {['Number ' num{2} ' in V1 in Store']};
end

当我尝试运行Compiler('3+1')时,输出为空。我试图逐步调试它,我发现当term函数完成并跳回表达式函数时,compiler.out2 x 1单元格数组变为空。

我对此感到困惑。我已经实现了与此类似的其他类,并且我们的类的私有函数可以更改它们的所有属性。

1 个答案:

答案 0 :(得分:4)

当您对类的实例进行更改时,如果您希望注册更改,则必须从handle类继承。如果不这样做,则假定返回对类实例所做的任何更改,并且必须有一个反映此值的输出变量。

因此,在类定义的顶部,继承自handle类:

classdef Compiler < handle

此外,您的类定义不太正确。您需要确保在expression termmethods内完全定义privateend。您在类定义的最后还缺少一个最终compiler.out,最后,您不需要在构造函数中回显classdef Compiler < handle %%%% CHANGE %UNTITLED2 Summary of this class goes here % Detailed explanation goes here properties(Access = public) in='' %a line of string of MATLAB code out={} %several lines of string(cell array) of Babbage Code end methods(Access = private) %%%% CHANGE function expression(compiler) %Compile(Parse and Generate Babbage code)one line of MATLAB code term(compiler); end %%%% CHANGE function term(compiler) % Read Number/Variable terms num = regexp(compiler.in, '[0-9]+','match'); len = length(compiler.out); compiler.out(len+1,:) = {['Number ' num{1} ' in V0 in Store']}; compiler.out(len+2,:) = {['Number ' num{2} ' in V1 in Store']}; end end methods(Access = public) function compiler = Compiler(str) compiler.in = str; expression(compiler); %compiler.out % don't need this end end end

Compiler(3+1)

现在,当我>> Compiler('3+1') ans = Compiler with properties: in: '3+1' out: {2x1 cell} 时,我得到:

out

变量>> celldisp(ans.out) ans{1} = Number 3 in V0 in Store ans{2} = Number 1 in V1 in Store 现在包含您正在寻找的字符串:

[[:digit:]]