类赋值运算符=问题

发布于 2024-12-03 08:22:36 字数 593 浏览 0 评论 0原文

假设我有两个类,位于两个不同的标头中,称为:

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 尚未定义时?

Say I have two classes, in two different headers, called:

class TestA
{
    public:
        int A;
};

class TestB
{
    public:
        int B;
};

And I want to give them both an assignment operator to each other, so it's like:

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;}
};

How do I do the above whilst avoiding the obvious error that will result from calling/using class TestB when it hasn't been defined yet?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

是你 2024-12-10 08:22:36

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

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

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 也遵循相同的基本结构。

You cannot have the function definitions in your files as written as that will require a circular dependency.

To solve, forward declare the classes and put their implementation in a separate files.

A's header file:

// 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's implementation file:

// A.cpp
#include "A.h"
#include "B.h"

A& A::operator=(const B& b)
{
   // implementation...
   return *this;
}

Follow the same basic structure for B as well.

倥絔 2024-12-10 08:22:36

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

If you include both header files in your .cpp file, it should work. Make sure that you have a full definition of both classes in the header files.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文