1

I encountered some issues while working on friend functions. I want to use a friend function that uses two different classes in parameters. Here is the sample of code:

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_ */

Both .cpp files for ObjectA and ObjectB are empty (empty constructor and destructor). Here is the main .cpp file:

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

This all thing sends me the following error :

'ObjectA' has not been declared

And this error is pointing to this line in the ObjectB.h :

friend void friendFunction(ObjectA &, ObjectB &);

As you can see, the ObjectA.h file has been included in the ObjectB.h file. So I don't know where my error come from.

Maybe I'm using friend function in a wrong way ?

Thank you guys !

4

2 回答 2

3

在 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.

于 2014-11-02T16:48:11.743 回答
0

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;
}
于 2014-11-02T17:04:15.047 回答