Typecast operator overloading problem

2019-08-30 16:01发布

问题:

For example i have two classes A and B, such that for two objects a and b, i want to be able to do :
A a;
B b;
a = b;
b = a;

for this i have overloaded the = operator, and the typecast operators as:

class A{
-snip-
    operator B()const { return B(pVarA); }
};
class B{
-snip-
    operator A()const { return A(pVarB); }
};

but when i try to compile this code, gcc throws the error :
error: expected type-specifier before 'B'
for the line: operator B()const { return B(pVarA);}

my guess is, this is due to a chicken and egg problem as class B is defined after class A.

Is there a way to circumvent this while still using the overloaded typecast operators. And if not, then what might be the best way to achieve my goals.

Any help will be appreciated. Thanks in advance.

回答1:

Try forward declaring then supplying the actual function definitions later on:

class B;

class A{
-snip-
    operator B()const;
};
class B{
-snip-
    operator A()const;
};

inline A::operator B() const
{
    return B(pVarA);
}

inline B::operator A() const
{
    return A(pVarB);
}


回答2:

This should work:

class B;

class A{
    operator B()const;
};

class B{
    operator A()const { return A(pVarB); }
};

A::operator B() const { return B(pVarA); }