假设我有两个类,在两个不同的标题中,名为:
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
也遵循相同的基本结构。
关于c++ - 类赋值运算符=问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7322585/