How do I implement a unary operator overload for a forward declared type in C++?
The following code does not compile in Visual Studio 2008. How do I get it to allow a unary operator in the Foo1 class that converts开发者_StackOverflow社区 it to a Bar, when Foo1 is defined before Bar?
class Foo1
{
public:
int val;
operator struct Bar() const;
};
struct Bar
{
int val;
};
// This does not compile
Foo1::operator Bar() const
{
Bar x;
x.val = val;
return x;
}
Or you could:
//forward declaration of Bar
struct Bar;
class Foo1
{
public:
int val;
operator Bar() const;
};
struct Bar
{
int val;
};
//Now it should compile
Foo1::operator Bar() const
{
Bar x;
x.val = val;
return x;
}
I figured out the answer. There are two solutions:
struct Bar;
class Foo1
{
public:
int val;
operator struct Bar() const;
};
Or:
class Foo1
{
typedef struct Bar MyBar;
public:
int val;
operator MyBar() const;
};
(The operator::Bar() implementation remains unchanged)
精彩评论