我在处理友元函数时遇到了一些问题。我想使用一个在参数中使用两个不同类的友元函数。以下是代码示例:
ObjectA.h:
#ifndef OBJECTA_H_
#define OBJECTA_H_
#include "ObjectB.h"
#include <iostream>
using namespace std;
class ObjectA {
private:
friend void friendFunction(ObjectA &,ObjectB &);
public:
ObjectA();
virtual ~ObjectA();
};
#endif /* OBJECTA_H_ */
ObjectB.h:
#ifndef OBJECTB_H_
#define OBJECTB_H_
#include <iostream>
using namespace std;
#include "ObjectA.h"
class ObjectB {
private:
friend void friendFunction(ObjectA &, ObjectB &);
public:
ObjectB();
virtual ~ObjectB();
};
#endif /* OBJECTB_H_ */
ObjectA和ObjectB的.cpp文件都为空(构造函数和析构函数为空)。以下是.cpp主文件:
#include <iostream>
using namespace std;
#include "ObjectA.h"
#include "ObjectB.h"
void friendFunction(ObjectA &objA, ObjectB &objB){
cout << "HIIIIIIIIIII";
}
int main() {
cout << "!!!Hello World!!!" << endl; // prints !!!Hello World!!!
return 0;
}
这一切都给我发送了以下错误:
'ObjectA' has not been declared
这个错误指向ObjectB.h:中的这一行
friend void friendFunction(ObjectA &, ObjectB &);
如您所见,ObjectA.h文件已包含在ObjectB.h文件中。所以我不知道我的错误是从哪里来的。
也许我使用朋友函数的方式不对?
谢谢你们!
在ObjectA.h中,替换:
#include "ObjectB.h"
带有:
class ObjectB;
在ObjectB.h 中进行相应的更改
发生的情况是main.cpp包含ObjectA.h。在声明ObjectA
类之前,ObjectA.h包含ObjectB.h。当ObjectB.h再次尝试包含ObjectA.h时,#ifndef OBJECTA_H_
测试失败,这意味着在声明友元函数时没有声明ObjectA
类,从而导致错误。
您可以在特定情况下使用前向类声明而不是#include
来打破这个循环。
Baybe是否使用模板函数?但通过这种方式,您将打破封装。
class A{
private:
template<typename T, typename B>
friend void friendFunc( const T&, const B&);
int m_a;
};
template<typename A, typename B>
void friendFunc( const A& a, const B& b){
std::cout << a.m_a << std::endl;
}
int main(int argc, char **argv) {
friendFunc<A, int>(A(), int(3));
return 0;
}