Class 调用方法时实例变量不保留更改

Class instance variable does not retain changes when method is called

我在 MATLAB 中创建了一个 class:

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 元胞数组变为空

我对此感到困惑。我已经实现了其他与此类似的 classes,它们的所有属性都可以通过我的 class 的私有函数进行更改。

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

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

classdef Compiler < handle

此外,您的 class 定义不太正确。您需要确保 expressiontermmethods 块中完全定义,即 private。您还在 class 定义的末尾缺少一个最终的 end 最后,您不需要在构造函数中回显 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