【问题标题】:Friend function that takes 2 classes in parameters - 'Class' not defined在参数中采用 2 个类的友元函数 - 未定义“类”
【发布时间】:2014-11-02 16:37:17
【问题描述】:

我在处理朋友功能时遇到了一些问题。我想使用一个在参数中使用两个不同类的朋友函数。这是代码示例:

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 文件中。所以我不知道我的错误来自哪里。

也许我以错误的方式使用朋友功能?

谢谢你们!

【问题讨论】:

    标签: c++ friend-function


    【解决方案1】:

    在 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 类,从而导致错误。 p>

    您可以在特定情况下使用前向类声明而不是#include 来打破此循环。

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-08-07
        • 2011-05-16
        • 1970-01-01
        • 1970-01-01
        • 2016-11-14
        • 1970-01-01
        • 1970-01-01
        • 2016-10-19
        相关资源
        最近更新 更多