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按 value传递句柄对象数组(包括 1×1“标量”数组)。句柄值是对对象的引用,可以用来改变对象的状态(即其属性),但重要的是,它不是对象本身。如果将句柄值数组传递给函数或方法,则实际上将数组的副本传递给函数,并且修改副本的维度对原始没有影响。事实上,当你打电话

TheOther.Instantiate;  

That您分配给的实例Self(1,1)作为 的输出返回Instantiate并分配给ans

这个指向MATLAB Object-Oriented Design 文档部分的链接也可能有所帮助。

于 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 回答