Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/codeigniter/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 复制构造函数时出错_C++_Copy Constructor - Fatal编程技术网

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)