c++ - 错误消息 : with Copy constructor and Overloaded assignment operator

标签 c++ overloading copy-constructor assignment-operator

这是我之前问的一个问题。 我在使用论坛建议的复制构造函数时遇到编译错误。

class A
{
private:
    int a;
    int b;


public:

    A() { a = 0; b = 0; }
    int getA() { return a; }
    int getB() { return b; }
    A(const Beta& b) :a{ *b.X() }, b{ *b.Y } {} 

};

class Beta
{
private:
    int *x;
    int *y;

public:
    Beta(int a, int b) { x =&a; y = &b; }
    int* X() { return x; }
    int* Y() { return y; }

};

int main()
{
    B aObject;
    Alpha a1 = aBObject;
    Alpha a2;
    a2 = aBObject;

    return 0;

}

复制构造函数参数中没有 const Alpha(Beta& be)

Error   C2061   syntax error: identifier 'Beta' 
Error   C2228   left of '.getY' must have class/struct/union 
Error   C2228   left of '.getX' must have class/struct/union 
Error   C2679   binary '=': no operator found which takes a right-hand operand of type 'Beta' (or there is no acceptable conversion)
Error   C2440   'initializing': cannot convert from 'Beta' to 'Alpha' 
Error   C2065   'be': undeclared identifier 
Error   C2535   'Alpha::Alpha(void)': member function already defined or declared 

在复制构造函数参数中使用 const Alpha(const Beta& be)

Error (active)  the object has type qualifiers that are not compatible with the member function "Beta::getX" 
Error (active)  the object has type qualifiers that are not compatible with the member function "Beta::getY" 

Error   C2061   syntax error: identifier 'Beta' 
Error   C2228   left of '.getY' must have class/struct/union 
Error   C2228   left of '.getX' must have class/struct/union 
Error   C2679   binary '=': no operator found which takes a right-hand operand of type 'Beta' (or there is no acceptable conversion)
Error   C2440   'initializing': cannot convert from 'Beta' to 'Alpha' 
Error   C2065   'be': undeclared identifier 
Error   C2535   'Alpha::Alpha(void)': member function already defined or declared

最佳答案

这是你想要的吗?

class Beta
{
private:
    int *x;
    int *y;

public:
    Beta() { x = nullptr; y = nullptr; }
    int* getX() { return x; }
    int* getY() { return y; }

};

class Alpha
{
private:
    int a;
    int b;


public:

    Alpha() { a = 0; b = 0; }
    int getA() { return a; }
    int getB() { return b; }
    Alpha( Beta& be) :a{ *be.getX() }, b{ *be.getY() } {} 
//It is not copy Constructor. You can't pass const reference here because getX getY returns pointer. So it could break const contract

};



int main()
{
    Beta aBetaObject;
    Alpha a1 = aBetaObject;
    Alpha a2;
    a2 = aBetaObject;

    return 0;

}

关于c++ - 错误消息 : with Copy constructor and Overloaded assignment operator,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57029766/

相关文章:

c++ - 复制构造函数与 pch 中的 const 成员函数冲突?海湾合作委员会的错误?

c++ 析构函数在程序结束前调用

c++ - 需要帮助从不同的功能输出东西(C++)

C++ 重载运算符 +

c++ - 非静态数据成员(数组)的使用无效

c++ - vector 的错误内存分配 C++

c++ - 尝试在给定节点之前删除

c++ - 如何运行套接字示例 C++?

PHP函数重载

java - 在复制构造函数中使用直接字段访问而不是 getter 会导致空指针异常