C++ 复制构造函数时出错
我的头文件如下所示:C++ 复制构造函数时出错,c++,copy-constructor,C++,Copy Constructor,我的头文件如下所示: class A { public: A(); A(A const & other); private: class B { public: B * child; int x; int y; void copy( B * other); }; B * root; void copy( B * other); }; 而我的cpp文件是: A::A() { root = NULL; } A::A
class A
{
public:
A();
A(A const & other);
private:
class B
{
public:
B * child;
int x;
int y;
void copy( B * other);
};
B * root;
void copy( B * other);
};
而我的cpp文件是:
A::A()
{
root = NULL;
}
A::A(A const & other)
{
if (other.root == NULL)
{
root = NULL;
return;
}
copy(other.root);
}
void A::copy( B * other)
{
if (other == NULL)
return;
this->x = other->x;
this->y = other->y;
this->child->copy(other->child);
}
然而,当我编译我的代码时,我得到一个错误-'类A没有名为x的成员'
我猜这是因为“x”是B类的成员,B类是私有的。是否可以在不更改头文件结构的情况下创建副本构造函数
我猜这是因为“x”是B类的成员,B类是
私人的
不,这是因为,正如错误所说,“类A没有名为x的成员”。类B
does。在函数A::copy
中,这个是指向A
对象的指针,但您试图通过它访问不存在的成员x
和y
。也许你的意思是:
this->root->x = other->x;
this->root->y = other->y;
您的代码似乎无法区分属于A
的字段和属于B
的字段。编写A的副本构造函数的正确方法似乎是:
void A::copy( B *other )
{
this.root = other;
}
为B编写副本构造函数是一件完全不同的事情,但我甚至不确定它是否与本例相关。在void a::copy(B*other)
中,this->x
意味着a::x
,而a没有x或yI在上面编辑了我的代码,将“copy”的定义包含在具有完全相同签名的B类中。这是否有任何我应该关注的影响?我这样做是为了允许我做this->child->copy(other->child)代码>