2016-08-23 5 views
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.out сменил с массива ячеек 2 x 1 на пустой.

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

ответ

4

Если вы вносите изменения в экземпляр своего класса, если вы хотите, чтобы изменения были зарегистрированы, вы должны наследовать от класса 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