Переменная экземпляра класса не сохраняет изменения при вызове метода

Я создал класс в 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.out изменились с 2 x 1 на пустые.

Я смущен этим. Я реализовал другие классы, подобные этому, и все их свойства могут быть изменены частной функцией моего класса.


person Michelle Shieh    schedule 23.08.2016    source источник


Ответы (1)


Когда вы вносите изменения в экземпляр своего класса, если вы хотите, чтобы изменения были зарегистрированы, вы должны наследоваться от класса handle. Если вы этого не сделаете, предполагается, что любые изменения, внесенные в экземпляр вашего класса, будут возвращены, и у вас должна быть выходная переменная, отражающая это.

Поэтому в верхней части определения вашего класса наследуйте от класса handle:

classdef Compiler < handle

Кроме того, ваше определение класса не совсем правильно. Вам необходимо убедиться, что expression и term полностью определены в блоке methods, то есть private. Вам также не хватает одного последнего 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
person rayryeng    schedule 23.08.2016