1

我在 C++ 之后在 MATLAB 中学习 OOP。我正在尝试创建一个静态函数来获取为类创建的 numOfInstances。此外,一个对象的变化应该反映其他对象的变化。下面是我的代码:

classdef (Sealed) Student < handle

  properties (GetAccess = 'public', SetAccess = 'public')
    Name;
    ID;

  end


  methods (Access = private)
    function obj = Student

    end
  end

  methods (Static)
    function singleObj = getInstances
        persistent localObj;

        if isempty(localObj) || ~isvalid(localObj)
            localObj = Student;

        end
        singleObj = localObj;

    end
  end

  methods (Static)
    function count = getNumInstances

        persistent objCount;

        if isempty(objCount)
            objCount = 1;
        else
            objCount = objCount + 1;
        end
        count = objCount;

    end
  end
end
4

1 回答 1

2

您需要增加构造函数中的实例数,而您目前没有这样做。这大概是我会怎么做

classdef cldef < handle
    methods (Static, Access = private)
        function oldValue = getOrIncrementCount(increment)
        % Private function to manage the counter
            persistent VALUE
            if isempty(VALUE)
                VALUE = 0;
            end
            oldValue = VALUE;
            if nargin > 0
                VALUE = VALUE + increment;
            end
        end
    end
    methods (Static)
        function value = getInstanceCount()
        % Public access to the counter cannot increment it
            value = cldef.getOrIncrementCount();
        end
    end
    methods
        function obj = cldef()
        % Increment the counter in the constructor
            cldef.getOrIncrementCount(1);
        end
    end
end
于 2013-03-26T07:15:38.463 回答