MATLAB:从空实例化到“空白”实例化的类

3
为什么我的实例化函数不能创建'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

如您所见,我的实例化并没有起作用,我不知道为什么?它应该使用非空但是空白的实例替换空实例,不是吗?
更新:
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

1
你的变量命名真是独具匠心 :) - Amro
这只是一个玩笑,对于到处都是foobar已经厌烦了:D - Carel
在我看来,具体的例子总是更好;比如一个带有“姓名”属性的“学生”类。 - Amro
我已经在实际代码中这样做了,下次也会在这里这样做:D - Carel
2个回答

2
MATLAB将句柄对象的数组(包括1x1的“标量”数组)按值传递。句柄值是对象的引用,可以用于更改对象的状态(即其属性),但重要的是,它并不是对象本身。如果您将句柄值数组传递给函数或方法,则实际上会传递一个副本到该函数,并且修改副本的维度对原始对象没有影响。事实上,在调用时,
TheOther.Instantiate;  

你将分配给`Self(1,1)`的`That`实例将作为`Instantiate`的输出返回,并分配给`ans`。
这里是一个MATLAB面向对象设计文档的链接,可能也会有所帮助。

那么,我如何将答案分配回TheOther的实例?我的理解是,进入Instantiate的Self参数应该是对TheOther实例的引用,然后我肯定可以填充原始实例?然后我就可以使实例非空了。但是遍历Props没有效果(上面发布过)。 - Carel
@Carel:你应该重新考虑你的类设计,Instantiate 不应该是一个成员函数;也许可以作为一个帮助函数,或者像我建议的那样是一个静态函数。 - Amro
请问您有什么建议吗?目前我正在考虑重写empty以创建一个空的项目集,然后重写isempty以声明如果它们的值是默认值,则它们为空。 - Carel

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

如果我必须这样做,那么更简单的方法是将TheOther赋值为That。我正在处理对象树,所以我真正要赋值给This.That.TheOther.Another.OrPossiblySomethingElse,并且希望在找到空分支时进行实例化。 - Carel
我不确定这是否有帮助,但是这个关于使用句柄类实例创建节点链表的演示可能会给你一些想法:http://www.mathworks.com/help/techdoc/matlab_oop/f2-86100.html - SCFrench
最终我选择了 Parent.Sub = Sub。感谢您的帮助。 - Carel

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接