没有对象的 MATLAB 构造函数/接口(interface)类

标签 matlab class oop constructor interface

MATLAB 中有没有一种方法可以构造某种不输出自己的对象的使用接口(interface)类或其他东西?我的想法是这样的:

object1_from_class_main = constructor_class_A()
object2_from_class_main = constructor_class_B()
object3_from_class_main = constructor_class_C()

其中 class_A/class_B/class_C 继承自 class_main。这意味着应该存在一个处理所有用户输入的main_class,并且在该类内部构造/维护所有其他子类。

我不知道这是否有很大的错误,但如果您有任何建议,我将不胜感激。

最佳答案

根据设计,构造函数必须返回构造函数所属类的对象 the output should be unassigned 。它不能返回不同类的对象。来自 the documentation .

The only output argument from a constructor is the object constructed. If you do not want to assign the output argument, you can clear the object variable in the constructor.

可以classAclassB等定义一个静态方法,返回类Main的对象>

classdef ClassA < handle
    methods (Static)
        function mainobj = create_main()
            % Construct Main object and do whatever you need to here
            mainobj = Main();
        end
    end
end

class_of_main = ClassA.create_main();

或者,您可以将 Main 实例设置为类的属性

classdef ClassA < handle

    properties
        mainobj
    end

    methods
        function self = ClassA()
            self.mainobj = Main()
        end
    end
end

更好的问题是为什么你需要这样做。

更新

根据您的说明,您基本上需要一个 Controller 来跟踪您创建的所有 Furniture 对象。您可以使用跟踪 Furniture 对象的类来完成此操作

classdef FurnitureController < handle
    properties
        furnitures = furniture.empty()
    end

    methods
        function addFurniture(self, furniture)
            self.furnitures = [self.furnitures, furniture];
        end
    end
end

classdef Furniture < handle
end

classdef Chair < Furniture
end

classdef Desk < Furniture
end

controller = FurnitureController()
controller.addFurniture(Desk())
controller.addFurniture(Chair())

关于没有对象的 MATLAB 构造函数/接口(interface)类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41572295/

相关文章:

matlab - 3D 数据中的平面提取

algorithm - Matlab - 从中​​点计算 1d 连续线段边缘的算法?

python - 我在尝试调用方法时收到名称错误

java - 如何访问类范围外但在父类范围内的变量?

java - 为什么我在 JUnit 的返回列表中得到额外的方括号

oop - Web 服务中 DTO 的命名约定是什么

Javascript有效的代码结构

matlab - matlab中的for循环迭代

matlab - 使用 mexCallMATLAB 将 Double* 转换为 mxArray* 的最有效方法

Python - 自引用类(使用魔术运算符进行向量加法)