开发者

How do I implement a unary operator overload for a forward declared type in C++?

开发者 https://www.devze.com 2023-02-04 22:16 出处:网络
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 Ba

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)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号