3

Instantiate関数がThatの「空白」インスタンスを作成しないのはなぜですか?

私は次の最小限のクラスを持っています:

classdef That < handle
 properties
  This = ''
 end
 methods
  function Self = That(String)
   if exist('String','var') == 1
    Self.This = String;
   end
  end
  function Self = Instantiate(Self)
   if isempty(Self)
    Self(1,1) = That;
   end
  end
 end
end

私が走ったら

This = That;
disp(size(This))     % 1x1
disp(isempty(This))  % False

そしてそれはすべて良いです、私はクラスの「空白」インスタンスを持っています

私が走ったら

TheOther = That.empty;
disp(size(TheOther))     % 0x0
disp(isempty(TheOther))  % True
TheOther.Instantiate;  
disp(size(TheOther))     % 0x0   - Expecting 1x1
disp(isempty(TheOther))  % True  - Expecting False

ご覧のとおり、Instantiateの実行が機能せず、理由がわかりません。確かに、空のインスタンスを空ではないが空白のインスタンスに置き換える必要がありますか?

アップデート :

SCFrenchからのリンクは、「空の配列の作成」という見出しの下にあるこのhttp://www.mathworks.com/help/techdoc/matlab_oop/brd4btr.htmlにつながりますが、これも機能しませんでした。

function Self = Instantiate(Self)
 if isempty(Self)
  Blank = That;
  Props = properties(Blank)
  for idp = 1:length(Props)
   Self(1,1).(Props{idp}) = Blank.(Props{idp});
  end
 end
end
4

2 に答える 2

2

MATLABは、ハンドルオブジェクトの配列(1行1列の「スカラー」配列を含む)を値で渡します。ハンドル値はオブジェクトへの参照であり、オブジェクトの状態(つまりそのプロパティ)を変更するために使用できますが、重要なのは、オブジェクト自体ではないということです。ハンドル値の配列を関数またはメソッドに渡すと、配列のコピーが実際に関数に渡され、コピーの次元を変更しても元の値には影響しません。実際、あなたが電話するとき

TheOther.Instantiate;  

Thatに割り当てたインスタンスはSelf(1,1)、の出力として返され、にInstantiate割り当てられansます。

MATLABObject-OrientedDesignドキュメントのセクションへのこのリンクも役立つ場合があります。

于 2012-06-19T14:54:34.933 に答える
0

多分あなたはそれを静的関数にするべきです:

methods (Static)
    function Self = Instantiate(Self)
        if isempty(Self)
            Self(1,1) = That;
        end
    end
end

それで:

>> TheOther = That.empty;
>> size(TheOther)
ans =
     0     0
>> isempty(TheOther)
ans =
     1
>> TheOther = That.Instantiate(TheOther);
>> size(TheOther)
ans =
     1     1
>> isempty(TheOther)
ans =
     0
于 2012-06-19T14:35:37.553 に答える