问题描述
我已经做了两个相同的类X和Y,带有指向对方的指针。参见下面的代码X.h,Y.h与所有X和Y的互换是相同的。然而,此代码在我的方法Connect中出现错误(错误C2027:使用未定义的类型'Y')。在X.h中,我已经向前声明了类Y,但是它不知道Y有一个名为SetXPointer的方法。因此我还需要转发声明这个方法,正确吗?
I have made two identical classes X and Y, with a pointer to each other. See the code below for X.h, Y.h is identical with all X's and Y's interchanged. This code gives however an error in my method Connect (error C2027: use of undefined type 'Y'). In X.h, I have forward declared the class Y, but it doesn't know that Y has a method named SetXPointer. Therefore I also need to forward declare this method, correct?
如果我尝试这样做(添加行Y :: SetXPointer(X * pX_in);在行类Y;),我得到一个编译器错误C2761: 'void Y :: SetXPointer(X *)':成员函数重新声明不允许。有没有办法在X类中使用Y类的公共方法?
If I try to do this (adding the line Y::SetXPointer(X* pX_in); under the line class Y;), I get a compiler error C2761: 'void Y::SetXPointer(X *)' : member function redeclaration not allowed. Is there a way to use a public method of class Y in class X?
// X.h
#pragma once
#include "Y.h"
// Forward declaration
class Y;
class X
{
public:
X(void) : data(24) {};
~X(void) {};
int GetData() { return data; }
void SetYPointer(Y* pY_in) { pY = pY_in; }
Y* GetYPointer() { return pY; }
void Connect(Y* Y_in) { pY = Y_in; Y_in->SetXPointer(this); }
private:
int data;
Y *pY;
};
推荐答案
不要在类体中包含方法体。写两个类,并且在两个类都完成后,编写方法实现:
Don't include the method body in the class body. Write both classes, and after both classes are complete, write the method implementations:
class Y;
class X {
…
void Connect(Y* Y_in);
…
};
class Y {
…
void Connect(X* X_in);
…
};
inline void X::Connect(Y* Y_in) {
pY = Y_in;
Y_in->SetXPointer(this);
}
inline void Y::Connect(X* X_in) {
pX = X_in;
X_in->SetXPointer(this);
}
这样,有关类的对象将如何布局的完整信息在实现 Connect
方法时可以使用内存。并且作为类体中的方法和声明 inline
的方法都将以相同的方式内联,性能也会一样。
That way, full information about how the objects of the class will be layed out in memory is available by the time the Connect
method is implemented. And as a method in the class body and a method declared inline
will both be inlined the same way, performance will be the same as well.
唯一的缺点是,你不能以合理的方式将这两个类拆分成两个头。
The only downside is that you won't be able to split these two classes over two headers in a reasonable way.
这篇关于如何转发声明一个类的成员函数在另一个类中使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!