【发布时间】:2015-04-16 10:05:59
【问题描述】:
Matlab 不允许定义不同的方法来定义具有不同参数列表的多个构造函数,例如这将不起作用:
classdef MyClass
methods
function [this] = MyClass()
% public constructor
...
end
end
methods (Access = private)
function [this] = MyClass(i)
% private constructor
...
end
end
end
但是,如上例所示,具有无法从公共接口调用的特定语法的 private 构造函数有时很有用。
在需要同时定义公共和私有构造函数的情况下,您将如何最好地处理?
检查调用堆栈???
classdef MyClass
methods
function [this] = MyClass(i)
if (nargin == 0)
% public constructor
...
else
% private constructor
checkCalledFromMyClass();
...
end
end
end
methods(Static=true, Access=Private)
function [] = checkCalledFromMyClass()
... here throw an error if the call stack does not contain reference to `MyClass` methods ...
end
end
end
定义一个辅助基类???
% Helper class
classdef MyClassBase
methods (Access = ?MyClass)
function MyClassBase(i)
end
end
end
% Real class
classdef MyClass < MyClassBase
methods
function [this] = MyClass()
this = this@MyClassBase();
end
end
methods (Static)
function [obj] = BuildSpecial()
obj = MyClassBase(42); %%% NB: Here returned object is not of the correct type :( ...
end
end
end
其他解决方案???
【问题讨论】: