简体   繁体   English

MATLAB构造函数/无对象的接口类

[英]MATLAB constructor / interface-class without object

is there a way in MATLAB to construct some kind of an use-interface-class or something, that does not output an own object? MATLAB中有没有一种方法可以构造某种不使用自己的对象的使用接口类或其他东西? I have something like this in mind: 我有这样的想法:

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

with class_A / class_B / class_C inherit from class_main . class_A / class_B / class_C继承自class_main This means there should exist a main_class that handles all user input, and inside of this class, all other subclasses are constructed/maintained. 这意味着应该存在一个main_class来处理所有用户输入,并且在该类内部,将构造/维护所有其他子类。

I dont know if there is a big mistake in this, but would appreciate, if you have any suggestions. 我不知道这是否有大错误,但如果您有任何建议,将不胜感激。

By design, the constructor must return an object of the class that the constructor belongs to or the output should be unassigned . 根据设计,构造函数必须返回该构造函数所属的类的对象, 或者 输出应未分配 It cannot return an object of a different class. 它不能返回不同类的对象。 From 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. 如果不想分配输出参数,则可以在构造函数中清除对象变量。

You could define a static method for classA , classB , etc. that returns an object of class Main 可以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();

Alternately, you could make your Main instance a property of your classes 或者,您可以将Main实例设为类的属性

classdef ClassA < handle

    properties
        mainobj
    end

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

A better question though is why you need to do this. 不过,一个更好的问题是为什么您需要这样做。

Update 更新

Based on your clarification, you want basically a controller to keep track of all of the Furniture objects that you create. 根据您的说明,您基本上希望控制器来跟踪您创建的所有Furniture对象。 You can do this with a class which keeps track of Furniture objects 您可以使用跟踪“ 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())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM