是否可以在构造函数中访问当前 'to create' 对象?
Is it possible to access the current 'to create' obj in constructor?
我目前正在写一棵树 class 并且想要实现一个构造函数来创建具有特定维度和深度的树:
public:
tree(); // empty constructor
tree(int dimension, int depth); // constructing an empty tree
// ...
void newNode(node<T>* const&, T const&);
// ...
private:
unsigned int mNumNodes;
node<T> *mRoot;
template<typename T>
tree<T>::tree(int dimension, int depth):
// member vars
{
// other constructing stuff
this->newNode(0, parent);
}
显然这样的事情是不可能的,但是当我写了一个很好的工作函数来将新节点添加到具有特定值的特定父节点时,使用它会很好。
但是:此方法需要访问当前对象。
也许有某种解决方案对我有用,既不能指向 obj,也不能进行任何其他类型的访问。
问题不在于构造函数。在执行进入构造函数主体时,对象被构造为 tree<std::basic_string<char> >
。这意味着您可以在构造函数的主体中将该对象用作 class 的实例。
在构造函数中使用对象本身的问题是,如果正在构造的实际对象是从手头的 class 派生的 class。这是父 class 的构造函数中尚不存在的知识。最好不要从构造函数中调用虚函数。从构造函数中调用非虚拟成员函数通常是可以的。另一个问题是派生的 class 构造函数可能会更改父 class.
中的内容
这不是这里发生的事情。这里的问题是使用零作为 node<T>* const&
。这行不通,期间。如果确实有效,您可以更改零值。
根据您发布的不完整代码,去掉 newNode
的第一个参数声明中的 & 符号即可。
我目前正在写一棵树 class 并且想要实现一个构造函数来创建具有特定维度和深度的树:
public:
tree(); // empty constructor
tree(int dimension, int depth); // constructing an empty tree
// ...
void newNode(node<T>* const&, T const&);
// ...
private:
unsigned int mNumNodes;
node<T> *mRoot;
template<typename T>
tree<T>::tree(int dimension, int depth):
// member vars
{
// other constructing stuff
this->newNode(0, parent);
}
显然这样的事情是不可能的,但是当我写了一个很好的工作函数来将新节点添加到具有特定值的特定父节点时,使用它会很好。
但是:此方法需要访问当前对象。
也许有某种解决方案对我有用,既不能指向 obj,也不能进行任何其他类型的访问。
问题不在于构造函数。在执行进入构造函数主体时,对象被构造为 tree<std::basic_string<char> >
。这意味着您可以在构造函数的主体中将该对象用作 class 的实例。
在构造函数中使用对象本身的问题是,如果正在构造的实际对象是从手头的 class 派生的 class。这是父 class 的构造函数中尚不存在的知识。最好不要从构造函数中调用虚函数。从构造函数中调用非虚拟成员函数通常是可以的。另一个问题是派生的 class 构造函数可能会更改父 class.
中的内容这不是这里发生的事情。这里的问题是使用零作为 node<T>* const&
。这行不通,期间。如果确实有效,您可以更改零值。
根据您发布的不完整代码,去掉 newNode
的第一个参数声明中的 & 符号即可。