1

我在 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单元格数组变为空。

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

4

1 回答 1

4

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

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

classdef Compiler < handle

此外,您的类定义并不完全正确。您需要确保expressionterm完全定义methodsprivate. 您在end类定义的末尾还缺少一个 final ,最后,您不需要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
于 2016-08-23T14:40:38.487 回答