通过第一类的构造函数返回第二类的对象 [英] Returning an object of a second class through the constructor of first class
问题描述
我有一个节点类和一个树类.我已经定义了节点类以包含节点声明所需的属性,并且该树类用于从节点形成树形结构.虽然树结构是由节点构成的,但是在返回节点对象时遇到了问题.我的代码结构是:
I have a node class and a tree class. I have defined the node class to contain the properties needed for a node declaration and the tree class is used to form a tree structure from the nodes. While the tree structure is formed from the node, I am having a problem in returning the node object. My code structure is:
classdef Node
properties
node_center;
node_size;
end
methods
function this = Node(center,size)
this.node_center = center;
this.node_size = size;
end
end
end % end of class Node
classdef Tree < handle
methods
function n = Tree(points,objects_in_tree)
n = Node(center_of_points,size);
n = insert_child(n,center,sizez);
end
end
现在我得到的错误是: 在构造类"Tree"的实例时,构造函数必须保留返回对象的类. 我知道其发生原因,但想知道解决方法.谢谢.
Now the error I am getting is: When constructing an instance of class 'Tree', the constructor must preserve the class of the returned object. I know the reason of why its happening but would like to know the workaround to this. Thanks.
推荐答案
构造函数的返回值必须是创建的对象-无法绕开它.您可以创建另一个函数,该函数返回您想摆脱的其他值(例如Node).构造完Tree之后,在该对象上调用accessor函数.
The return value from the constructor must be the object created - there's no way around it. You can make another function that returns the other values (like the Node) that you would like to get out of it. After the Tree is constructed, call the accessor function on that object.
这篇关于通过第一类的构造函数返回第二类的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!