Matlab - 处理唯一对象的对象属性指的是同一个对象?

标签 matlab oop

我对如何在 matlab 中将句柄对象用作属性感到困惑。例如,我定义了以下类:

classdef Page < handle
properties
    word1;
    word2;
end

classdef Book < handle
properties
    page1 = Page;
    page2 = Page;
end

现在我实例化两本书:

iliad = Book;
odyssey = Book;

如果我检查 iliad 和 odyssey 是否相同:

eq(iliad, odyssey)

我得到:

ans = logical 0

到目前为止一切顺利

但是如果我检查 iliad 和 odyssey 的 page1 是否相同:

eq(iliad.page1, odyssey.page1)

我得到:

ans = logical 1

这可不好!这意味着如果我更改 odyssey 的 page1,iliad 的 page1 也会更改。我误会了什么?我该如何处理这个问题?

最佳答案

这似乎与 MATLAB 如何计算属性默认值有关。根据 Properties Containing Objects 的文档:

MATLAB® evaluates property default values only once when loading the class. MATLAB does not reevaluate the assignment each time you create an object of that class. If you assign an object as a default property value in the class definition, MATLAB calls the constructor for that object only once when loading the class.

它进一步指出:

Evaluation of property default values occurs only when the value is first needed, and only once when MATLAB first initializes the class. MATLAB does not reevaluate the expression each time you create an instance of the class.

这描述了您在书籍之间看到的平等。 MATLAB 本质上是 caches class definitions ,因此虽然您的 Page 对象在本书中有所不同,但它们在各本书中都是相同的,因为 MATLAB 仅构造一次默认值。

为避免这种情况,您可以在 Book 的构造函数中实例化您的 Page 对象:

classdef Book < handle
properties
    page1
    page2
end

methods
    function self = Book()
        self.page1 = Page;
        self.page2 = Page;
    end
end
end

这给了你想要的行为:

>> iliad = Book;
>> odyssey = Book;
>> eq(iliad.page1, odyssey.page1)

ans =

  logical

   0

关于Matlab - 处理唯一对象的对象属性指的是同一个对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49370627/

相关文章:

matlab - 如何重新调整直方图的高度?

java - 有没有办法在类之间使用方法?

c++ - 避免不必要地添加抽象函数以适应新功能的设计模式

c# - IoC、SRP 和组合——我是否创建了太多接口(interface)?

matlab - 如何参数化作为高斯导数的曲线

matlab - 通过将方法的名称和输入传递给函数/方法来处理 Matlab 中未定义的方法

c++ - 错误 : mclmcr. h:没有这样的文件或目录从 C 调用 matlab 函数

matlab - 基于多种条件的逻辑索引

javascript - "class"中的嵌套函数

c# - 有没有办法在实例化对象时隐藏/显示某些方法?