سؤال

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 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;
}
هل كانت مفيدة؟

المحلول 2

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)

نصائح أخرى

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;
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top