Matlab - 从另一个方法matlab调用一个方法

时间:2016-03-16 17:39:22

标签: matlab oop methods

两个班级:

classdef first < handle
    methods
        function hello(obj)
            disp('hello ok')
            obj_second.bye
        end
    end
end

classdef second < handle
    methods
        function bye(obj)
            disp('bye ok')
        end
    end
end

我希望能够从obj_first调用obj_second.bye。

>> obj_first=first;
>> obj_second=second;
>> obj_first.hello
hello ok
Undefined variable "obj_second" or class "obj_second.bye".

Error in first/hello (line 5)
            obj_second.bye

>> 

obj_second似乎必须在类“first”中构造才能被这个类考虑;你觉得怎么样?

1 个答案:

答案 0 :(得分:1)

hello方法中,您只能访问代表第一个类的当前实例的本地变量obj来调用它(例如此处为obj_first)并且可能是班级的properties。但是您无法访问其他外部变量,例如obj_second

为此,您必须将其作为参数传递:

classdef first < handle
    methods
        function hello(obj, obj2)
            disp('hello ok')
            obj2.bye()
        end
    end
end

>> obj_first.hello(obj_second)
相关问题