Forward declaration with friend function: invalid use of incomplete type

冷暖自知 提交于 2019-12-01 17:32:50

问题


#include <iostream>

class B;

class A{
 int a;
public:
 friend void B::frndA();
};

class B{
 int b;
public:
 void frndA();
};

void B::frndA(){
 A obj;
 std::cout << "A.a = " << obj.a << std::endl;
}

int main() {
 return 0;
}

When trying to compile this code, some errors occurred. E.g.

invalid use of incomplete type

What are the problems in this code?


回答1:


Place the whole of the class B ... declaration before class A. You haven't declared B::frndA(); yet.

#include <iostream>
using namespace std;

class B{
    int b;
public:
    void frndA();
};

class A{
    int a;
public:
    friend void B::frndA();
};



void B::frndA(){
    A obj;
    //cout<<"A.a = "<<obj.a<<endl;
}

int main() {
    return 0;
}



回答2:


The problem is you can't friend a member function before the compiler has seen the declaration.

You are going to need to rearrange your code to solve the problem (i.e. move the definition of class B prior to class A).




回答3:


You need to put the declaration of B before A. The compiler doesn't know about this: B::frndA(). A forward declaration is not enough information to infer what members the type has.

I would recommend to put your class A declaration in a file A.h and it's definition inside a file A.cpp. Likewise the same for the type B inside of B.h and B.cpp

At the top of each header file put #pragma once (or if you prefer include guards).

Then inside your B.h you can simply include A.h.



来源:https://stackoverflow.com/questions/3183710/forward-declaration-with-friend-function-invalid-use-of-incomplete-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!