开发者

Class assignment operator= question

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 Test开发者_开发问答B& 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?


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜