【问题标题】:Why are the values passed to a method saved as an object?为什么将传递给方法的值保存为对象?
【发布时间】:2015-07-17 17:59:29
【问题描述】:

我有一个带有调度程序函数的类,它应该将字符插入到元胞数组中:

classdef timeline < handle
properties
    schedule
    i
    %other properties
end

methods
    %other functions
    function t = timeline()
         %other initializations
         t.schedule = cell(1,738);
         t.i = 1;
    end
    function scheduler(t, g, fT)
        if nargin == 2
            fT = t.i;
        end
        if strcmp(g,'science')
            'science' % eclipse occurs after
            for j = (fT+t.sTime+1) : (fT+t.sTime+1+t.eTime)
                t.schedule{j} = 'e';
            end
        elseif strcmp(g,'pass')
            'pass' % science occurs 2 hrs after end
            for j = (fT) : (fT+t.pTime)
                t.schedule{j} = 'p'
            end
            for j = (fT+t.pTime+121) : (fT+t.pTime+120+t.sTime)
                t.schedule{j} = 's';
            end
            scheduler(t, 'science', fT+t.pTime+120);
        end
    end
end
end

在命令窗口中,我定义了我的对象t = timeline() 和一个模式g = 'pass',然后调用调度程序t.scheduler(t,g)

它不会更改 schedule 属性。 if 语句中编写日程表的内容不是我关心的问题。我将输出放在if 语句的每个部分,发现strcmp 返回false 并跳过整个块。所以,我在调度器函数中添加了一个断点,发现由于某种原因g作为另一个timeline对象而不是字符串'pass'传递给函数。这是为什么呢?

【问题讨论】:

    标签: matlab class argument-passing


    【解决方案1】:

    当您为对象调用方法时,您可以使用点表示法或函数表示法。点表示法意味着您在对象实例上使用点运算符调用方法。例如,

    obj.methodName(args);
    

    在函数表示法中,您将对象实例变量作为第一个参数传递给方法。例如,

    methodName(obj, args);
    

    上述两个调用是等价的,并且在对象中调用相同的方法。在这两个调用中,MATLAB 将 obj 作为输入传递给方法。请注意在点符号中没有 obj 作为参数。在点符号 obj 中,作为输入参数添加到您的 args 之前。在您的代码中,您混合了这两个选项。所以你的方法有两个 obj 参数。

    相关文档位于http://www.mathworks.com/help/matlab/matlab_oop/method-invocation.html

    【讨论】:

    • 啊,我明白了。感谢您的链接。
    猜你喜欢
    • 2012-03-28
    • 1970-01-01
    • 2013-12-24
    • 1970-01-01
    • 2013-10-23
    • 2017-06-21
    • 2019-01-02
    • 2016-11-20
    • 2020-02-10
    相关资源
    最近更新 更多