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