我对如何在 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/