类赋值操作符=问题

Class assignment operator= question

本文关键字:问题 赋值操作符      更新时间:2023-10-16

假设我有两个类,在两个不同的头文件中,名为:

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文件中包含两个头文件,它应该工作。确保在头文件中有两个类的完整定义。