2012-06-19 37 views
3

为什么我的实例化函数没有创建一个'空白'实例?MATLAB:将一个实例从一个空实例实例化到一个'空白'实例

我有以下最小类:

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不起作用,我不明白为什么?当然,它应该用一个非空的空白实例替换空实例吗?

UPDATE:

从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

+0

这是一个关于这方面的游戏,以及其他的,厌倦了看到foobar无处不在:D – Carel

+0

IMO具体例子总是更好;像'学生'类与'名称'属性 – Amro

回答

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 
+0

如果我必须这样做,那么做更简单的TheOther =那。我真的在用对象树工作,所以我真的分配到This.That.TheOther.Another.OrPossiblySomethingElse,并且真的想实例化,因为我找到空的bracnches。 – Carel

+0

我不确定这是否有帮助,但是关于使用句柄类实例创建节点链表的示例可能会给您一些建议:http://www.mathworks.com/help/techdoc/matlab_oop/f2-86100。 html – SCFrench

+0

最后我用'Parent.Sub = Sub'去了。感谢您的帮助 – Carel

2

MATLAB通过值传递句柄对象(包括1乘1“标量”数组)的数组。句柄值是对对象的引用,可用于更改对象的状态(即其属性),但重要的是,它不是对象本身。如果将一组句柄值传递给函数或方法,则数组的副本实际上被传递给该函数,并且修改副本的尺寸对原始文件没有影响。事实上,当你调用

TheOther.Instantiate; 

您分配给Self(1,1)That实例被返回的Instantiate输出和分配给ans

This link到MATLAB面向对象设计文档的一部分也可能有所帮助。

+0

那么我怎样才能得到ans分配给TheOther的实例呢?我的理解是,进入实例化的参数Self应该是对其他实例的引用,那么我肯定能够填充原始实例?然后我可以让这个实例非空。通过道具迭代不起作用(上面发布) – Carel

+0

@Carel:你应该真的重新考虑你的类设计,'Instantiate'不应该是一个成员函数;也许是一个帮手功能,或者像我建议的一个静态功能.. – Amro

+0

我可以问你会建议吗?目前我正在考虑覆盖空白以创建一组空的项目,然后重写isempty以声明如果它们的值是默认值,则它们是空的。 – Carel

相关问题