错误消息:使用复制构造函数和重载赋值运算符
Error messages: with Copy constructor and Overloaded 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;
}
代码中没有复制构造函数(或赋值运算符(。但无论如何,这不是问题所在。它们发出您的代码Alpha
使用Beta
Beta
之前发出问题。这就是编译器所抱怨的,它在你第一次使用它时无法识别Beta
。
只需移动Beta
,使其定义在Alpha
之前,一切都将编译。
相关文章:
- 当有右值构造函数可用时,为什么从右值调用类引用构造函数重载?
- 两种类型的构造函数重载
- C++ 构造函数重载 - 为什么说我需要括号?
- C++具有多重继承的构造函数重载解析
- C++,处理多个构造函数重载和冗余代码
- c++ 构造函数重载歧义与initializer_list
- 父类有 26 个构造函数重载.如何在不复制+粘贴 26 个重载的情况下将一个小任务附加到所有构造器?
- 用户定义的构造函数重载与参数超类的重载不匹配
- 模板专用类之间的构造函数重载
- 指向构造函数重载的指针?
- C++简化了构造函数重载
- 类构造函数重载不起作用
- C++类模板构造函数 -- 重载引用 (U&) 与数组 (U*) 失败
- 为什么存在 C++11 std::initializer_list 构造函数重载规则
- 构造函数重载和默认参数
- 模板类构造函数重载解析
- 单例中的构造函数重载不起作用
- 构造函数重载选择了强制转换运算符而不是结构类型
- c++ 11构造函数重载解析和initialiser_lists: clang++和c++不一致.< / h1 &
- C++构造函数重载的经验法则