gpt4 book ai didi

matlab - 验证属性是 MATLAB 中抽象类的子类

转载 作者:行者123 更新时间:2023-12-05 01:15:06 25 4
gpt4 key购买 nike

我是 Matlab 中的 OOP 的新手,在一般的 OOP 方面仍然相当新手,但我所知道的是我在 C++ 中学到的。

我正在关注此处的 Matlab 文档 Property class and size validation .我想验证一个属性,使其必须是一个特定的类,并且我正在使用链接中的示例。这是我的类(class)的样子:

classdef simpoint
...
properties
...
outputType dataType
...
end
...
end

在我的代码中,dataType 是我编写的一个类。更重要的是它是抽象的。

我收到了错误

Error defining property 'outputType' of class 'simpoint':
Class dataType is abstract. Specify a default value for property outputType.

dataType 类是抽象的,用于强制用户实现某些方法。我正在尝试使用属性验证来确保设置 outputType 时,该类是 dataType 的子类。

我并不想设置默认值,因为忘记设置 outputType 会引发错误。

如何验证 outputType 以确保它是 dataType 的子类?在 Matlab 中有没有更好的方法来做到这一点?

最佳答案

这个问题有一个更优雅的解决方案,这显然不是众所周知的。

MATLAB 有一个 Heterogeneous Class Hierarchies 的概念.这只是显式声明公共(public)根类(抽象或非抽象)的奇特方式,以便它可以用于属性验证。在实践中,您需要做的就是让您的抽象类继承自 matlab.mixin.Heterogeneous

这是一个简单的例子:

classdef (Abstract) AbstractItem < handle & matlab.mixin.Heterogeneous
end
classdef Collection < handle
properties
items AbstractItem
end
end

那你就没有问题了:

>> x = Collection

x =

Collection with properties:

items: [0×0 AbstractItem]

如果没有 matlab.mixin.Heterogeneous 继承,您将收到您描述的错误:

Error defining property 'items' of class 'Collection'. Class AbstractItem is abstract. Specify a default value for property items.

关于matlab - 验证属性是 MATLAB 中抽象类的子类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56901086/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com