【问题标题】:How to count the num of instances created, using a static function in MATLAB?如何使用 MATLAB 中的静态函数计算创建的实例数?
【发布时间】:2013-03-26 05:09:09
【问题描述】:

我在 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

【问题讨论】:

    标签: oop matlab singleton


    【解决方案1】:

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

    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
    

    【讨论】:

      猜你喜欢
      • 2014-03-02
      • 1970-01-01
      • 1970-01-01
      • 2022-06-29
      • 1970-01-01
      • 2022-08-22
      • 1970-01-01
      • 1970-01-01
      • 2022-12-20
      相关资源
      最近更新 更多