Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
336 views
in Technique[技术] by (71.8m points)

c++ - incomplete type error

Im trying to make class A a friend of class B.

class B;

class A{
public:
void show(const B&); // ##1## but this one works fine  
B ob;// error incomplete type

};


class B{
public:
int b;
B():b(1){}
friend class A;  

};

so my question why it's incomplete type? I thought that when I did class B it's like a prototype of a function which tell the compile there is a definition somewhere in the code.

also in the code above at ##1## why this is possible ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

No, that's a forward declaration and does not define a full type. You'll need to have a full definition of B before A, if you want to keep the member as an object and not pointer.

One of the reason for this is that the size of the class B must be known to A, since A's size depends on B.

I suggest you #include "B.h" in A.h.

EDIT: clarification:

struct A;

struct B
{
   A foo();
   void foo(A);
   void foo(A&);
   void foo(A*);

   A* _a;
   A& __a;
   A a;  // <--- only error here
};

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...