incomplete type error , when using friend functions
#include <stdio.h>
class B;
class A;
c开发者_运维问答lass A
{
int a;
friend int B::f();
};
class B
{
int b;
class A x;
public:
int f();
};
int B::f()
{
// ...
}
main()
{
class B b;
b.f();
}
ERRORS:
a.cpp:9: error: invalid use of incomplete type ‘struct B’
a.cpp:2: error: forward declaration of ‘struct B’
The issue cannot be solved by placing definition of B before A as B has an object of type A.
For this example making B a friend class would do, but in my real code I have more member functions in B (so I need alternative solution).
Finally, can somebody give me links that explain what the compiler does when it comes across a forward declaration, declaration, definition.
You simply cannot do what you want to do as-is. To make that friend function declaration in class A
the nature of class B
needs to be known prior to the definition of class A
. To make class B
contain an instance of class A
the nature of class A
must be known prior to the definition of class B
. Catch-22.
The former does not apply if you make class B
a friend class of class A
. The latter does not apply if you modify B
to contain a pointer or reference to an instance of class A
.
DefineB
before A
, and declare a pointer to A
as member data of B
:
class A; //forward declaration
class B
{
int b;
A *px; //one change here - make it pointer to A
public:
int f();
};
class A
{
int a;
friend int B::f();
};
Or, you could make the entire class B
a friend of A
, that way you don't have to make the member data pointer to A
.
class B; //forward declaration
class A
{
int a;
friend class B;
};
class B
{
int b;
A x; //No change here
public:
int f();
};
Forward declare class A; define class B; define class A; define B::f.
#include <cstdio>
class A;
class B
{
int b;
public:
int f();
};
class A
{
int a;
friend int B::f();
};
int B::f()
{
}
main()
{
class B b;
b.f();
}
精彩评论