类赋值运算符=问题

时间:2011-09-06 15:45:08

标签: c++ assignment-operator

假设我在两个不同的标题中有两个类,名为:

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而导致的明显错误?

2 个答案:

答案 0 :(得分:6)

您不能在文件中使用函数定义,因为这需要循环依赖。

要解决,请转发声明类并将其实现放在单独的文件中。

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的基本结构。

答案 1 :(得分:1)

如果在.cpp文件中包含两个头文件,它应该可以正常工作。确保在头文件中有两个类的完整定义。

相关问题