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.
您可以为classA
、classB
等定义一个静态方法,返回类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/