Forward declaration doesn't work with conversion operator
Consider the next code :
#include <iostream>
using namespace std;
class B;
class A
{
public:
开发者_StackOverflow中文版 A() { p = 1;}
int p;
operator B() {B b; b.x = this->p; return b;}
};
class B
{
public:
int x;
};
int main()
{
A a;
B b = a;
return 0;
}
I'm trying to convert A
to B
, but I get the following compiler scream :
..\main.cpp:13: error: return type 'struct B' is incomplete
When I do this :
#include <iostream>
using namespace std;
class B
{
public:
int x;
};
class A
{
public:
A() { p = 1;}
int p;
operator B() {B b; b.x = this->p; return b;}
};
int main()
{
A a;
B b = a;
return 0;
}
the code compiles , but the question is : is it possible to do that using the forward declaration I wrote above ?
Much thanks Ronen
Yes, it is possible, as long as the definition of A::operator B
follows the definition of class B
.
#include <iostream>
using namespace std;
class B;
class A
{
public:
A() { p = 1;}
int p;
operator B();
};
class B
{
public:
int x;
};
inline A::operator B() {B b; b.x = this->p; return b;}
int main()
{
A a;
B b = a;
return 0;
}
No. Your A::operator B()
creates an object of type B
. The compiler needs to know the definition of B
in order to be able to create an object of type B
(for instance, it needs to know how big it is to perform stack-pointer calculations. It needs to know whether custom constructors need to be called.)
The line:
operator B() {B b; return b;}
creates an object of B. This cannot happen since B isn't defined.
Forward declarations let you declare pointers to objects which can be created later when the object definition is known, but you can't create the objects straight off the bat.
No, it's not possible. You cannot declare an object of type which is not completely defined.
You can't do this with the forward declaration because the compiler needs to know the size of B
(and its default ctor as well) for the operator return type. Without a complete type, it cannot know the size.
Yes, it probably could get this information from the definition you provide below, but for historical reasons, C and C++ compilers only consider definitions that come before in a translation unit.
It is not possible to create an object of a class without knowing its definition.
Separate your implementation into .h and .cpp files. So you can have a forward declaration class B
in A.h
and include its definition in A.cpp
精彩评论