类赋值操作符=问题
Class assignment operator= question
假设我有两个类,在两个不同的头文件中,名为:
class TestA
{
public:
int A;
};
class TestB
{
public:
int B;
};
我想给它们一个赋值操作符,就像:
class TestB; //Prototype of B is insufficient to avoid error with A's assignment
class TestA
{
public:
int A;
const TestA &operator=(const TestB& Copy){A = Copy.B; return *this;}
};
class TestB
{
public:
int B;
const TestB &operator=(const TestA& Copy){B = Copy.A; return *this;}
};
我如何做到以上,同时避免调用/使用类TestB时尚未定义的明显错误?
你不能把函数定义写成需要循环依赖的形式。
要解决这个问题,可以向前声明类,并将它们的实现放在单独的文件中。
A
的头文件:
// A.h
// forward declaration of B, you can now have
// pointers or references to B in this header file
class B;
class A
{
public:
A& operator=(const B& b);
};
A
的实现文件:
// A.cpp
#include "A.h"
#include "B.h"
A& A::operator=(const B& b)
{
// implementation...
return *this;
}
B
也遵循相同的基本结构
如果您在.cpp
文件中包含两个头文件,它应该工作。确保在头文件中有两个类的完整定义。
相关文章:
- c++中的重载赋值操作符
- c++类继承和赋值操作符
- 带引用类成员的赋值操作符
- 复制构造函数,赋值操作符重载
- c++派生类赋值操作符
- 通过调用Move赋值操作符实现Move构造函数
- 带有映射的赋值操作符
- 单参数构造函数和赋值操作符
- 如何从复制赋值操作符调用复制构造函数
- c++复制构造函数,重载赋值操作符,方法get()
- 用于具有const数据成员的类的move和右值赋值操作符
- 类赋值操作符和复制构造函数
- 赋值操作符重载
- 影响正确性的move构造函数/赋值操作符示例
- 当类是子类时重载赋值操作符
- 如果没有定义Move语义(Move构造函数和Move赋值操作符),编译器是否默认优化
- 在类赋值操作符函数中,为什么必须返回*this ?
- 模板类的重载赋值操作符
- 类赋值操作符=问题
- c++赋值操作符关于继承的问题