【问题标题】:error on copy constructor复制构造函数错误
【发布时间】:2013-11-30 05:07:07
【问题描述】:

我的头文件是这样的:

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);
}

但是,当我编译我的代码时,我得到了错误 - 'class A has no member named x'

我猜这是因为“x”是私有的 B 类的成员。是否可以在不改变头文件结构的情况下制作复制构造函数。

【问题讨论】:

  • in void A::copy(B* other), this->x 表示A::x 并且A没有x或y

标签: c++ copy-constructor


【解决方案1】:

我猜这是因为“x”是 B 类的成员,它是 私人的。

不,这是因为,正如错误所说,“A 类没有名为 x 的成员”。 B 类可以。在函数A::copy 中,this 是指向A 对象的指针,但您正试图通过它访问不存在的成员xy。也许你的意思是:

this->root->x = other->x;
this->root->y = other->y;

【讨论】:

  • 我已经编辑了上面的代码,以在 B 类中包含一个具有完全相同签名的“复制”定义。这会产生我应该关注的任何影响吗?我这样做是为了让我可以这样做this->child->copy(other->child);
【解决方案2】:

您的代码似乎无法区分属于A 的字段和属于B 的字段。写A的拷贝构造函数的正确方法似乎是:

void A::copy( B *other )
{
    this.root = other;
}

为 B 编写一个复制构造函数是完全不同的事情,但我不确定它是否与这个示例相关。

【讨论】:

    猜你喜欢
    • 2023-04-01
    • 1970-01-01
    • 2017-08-18
    • 1970-01-01
    • 2014-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-02
    相关资源
    最近更新 更多