Matlab 不允许定义不同的方法来定义具有不同参数列表的多个构造函数,例如这将不起作用:

classdef MyClass 
 
    methods 
        function [this] = MyClass() 
            % public constructor 
            ... 
        end         
    end     
    methods (Access = private) 
        function [this] = MyClass(i) 
            % private constructor 
            ... 
        end 
    end 
 
end 

但是,如上例所示,有时使用无法从公共(public)接口(interface)调用的具有特定语法的私有(private)构造函数很有用。

您如何最好地处理这种需要同时定义公共(public)和私有(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 

其他解决方案???

请您参考如下方法:

我曾经尝试解决此限制的一个偷偷摸摸的技巧是使用另一个只能由 MyClass 构造的“标记”类,然后使用它来计算哪个构造函数你需要的变体。这是一个简单的草图:

classdef MyClass 
    properties 
        Info 
    end 
    methods 
        function o = MyClass(varargin) 
            if nargin == 2 && ... 
                       isa(varargin{1}, 'MyTag') && ... 
                       isnumeric(varargin{2}) && ... 
                       isscalar(varargin{2}) 
                o.Info = sprintf('Private constructor tag: %d', varargin{2}); 
            else 
                o.Info = sprintf('Public constructor with %d args.', nargin); 
            end 
        end 
    end 
    methods (Static) 
        function o = build() 
        % Call the 'private' constructor 
            o = MyClass(MyTag(), 3); 
        end 
    end 
end 

classdef MyTag 
    methods (Access = ?MyClass) 
        function o = MyTag() 
        end 
    end 
end 

请注意 Access = ?MyClass 说明符,这意味着只有 MyClass 可以构建 MyTag 的实例。在文档中有更多关于使用这种方法属性的信息:http://www.mathworks.com/help/matlab/matlab_oop/method-attributes.html


评论关闭
IT序号网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!