パブリックとして宣言しているため、直接アクセスできます。
classObj = MyClass;
classObj.MyProperty = 20;
classObj.MyProperty % ans = 20
しかし、それをカプセル化したいようです。いくつかの方法があります。次のように、プライベートアクセスを使用しているとします。
classdef MyClass
properties (Access = private)
MyProperty;
end
methods
function this = MyClass()
% initialize the class
this.MyProperty = [];
this.LoadProperty(2,2);
end
function p = GetProperty(this)
p = this.MyProperty;
end
function this = LoadProperty(this, m, n)
% loads the property
this.MyProperty = zeros(m, n);
end
end
end
次に、次のように set メソッドを追加できます (通常、関数と変数には小文字を使用し、クラスには大文字を使用します。必要に応じて大文字に変更できます)。
function this = setProperty(this,value)
this.MyProperty = value;
end
これはハンドル クラスではないため、この関数を次のように使用する必要があります。
myClass = myClass.setProperty(30); % You can also set it to [30 30 30; 20 20 20] if you want, there are no restrictions if you don't explicitly write into your function.
それ以外の場合は、次のようにしてハンドル クラスを使用できます。
classdef MyClass < handle
この場合、次のようにして直接変更できます。
myClass.setProperty(40);
ただし、これは、このクラスへの参照は新しいオブジェクトを作成せず、このオブジェクトからの別のハンドルになることも意味します。つまり、次の場合です。
myClass2 = myClass;
% and uses myClass2.setProperty:
myClass2.setProperty(40)
myClass.GetProperty % ans = 40!
したがって、この種の動作を回避したい場合 (つまり、クラスを関数または別の変数に渡すときにクラスのコピーが必要な場合、別名、値による呼び出し)、get および set メソッドの方法を指定したい場合Matlab は、プロパティを割り当てるときにオーバーロードできる 2 つの組み込みメソッドを提供します。あれは:
function out = get.MyProperty(this)
function set.MyProperty(this,value)
これらのメソッドを上書きすることで、ユーザーが呼び出したときに何が起こるかを上書きしています
myClass.MyProperty % calls out = get.MyPropertyGet(this)
myClass.MyProperty = value; % calls set.MyProperty(this,value)
ただし、ハンドル クラスを操作して、クラスのコピー関数を作成することもできます。
function thisCopy = copy(this)
nObj = numel(this);
thisCopy(nObj) = MyClass;
meta = metaclass(MyClass);
nProp = numel(meta,'PropertyList');
for k = 1:nObj
thisCopy(k) = MyClass; % Force object constructor call
for curPropIdx=1:nProp
curProp = meta.PropertyList(curPropIdx);
if curProp.Dependent
continue;
end
propName = curProp.Name;
thisCopy(k).(propName) = this(k).(propName);
end
end
end
これはget.
set.
、classdef 内で public メソッドとして (メソッドと同様に) 指定する必要があります。このメソッドを宣言してclass2
、 のコピーにしたい場合は、次のclass
ようにします。
myClass = MyClass;
myClass.setProperty(30);
myClass2 = copy(myClass);
myClass2.setProperty(40); %
myClass.GetProperty % ans = 30
handle
クラスオブジェクトからすべての(非)プロパティをコピーし、クラスオブジェクト配列があるときに機能するため、 MyClass にする必要があるのはもう少し複雑です。詳細については、@Amro の回答とmatlab oop のドキュメントを参照してください。
これは、機能する理由と機能しない理由の説明でもありthis = this.LoadProperty
ますthis.LoadProperty(2,2)
。