类赋值运算符=问题
假设我有两个类,位于两个不同的标头中,称为:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您不能在文件中包含函数定义,因为这将需要循环依赖。
要解决此问题,请转发声明类并将其实现放在单独的文件中。
A
的头文件:A
的实现文件: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
's implementation file:Follow the same basic structure for
B
as well.如果您在
.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.