c++ - 类赋值运算符=问题

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

最佳答案

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

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

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/

相关文章:

c++ - 通过 TCP 套接字发送 XDR 的好方法

c++ - 当我尝试进行 TPC-E 测试时,Make 实用程序提示 "undefined reference"

C++:为什么程序从输入文件中读取最后一个空白作为元素

c++ - 复制构造函数知识

c++ - 有没有人发现需要声明一个复制赋值运算符的返回参数const?

c++ - 最简单的 Qt 对话框

c++ - 在继承的对象中切片

c++ - 在此代码中调用赋值运算符的位置在哪里?

c++ - 编译器为具有引用和常量成员的类生成的复制/赋值函数

c++ - 回文在 C++ 函数中返回 false