Typecast operator overloading problem

柔情痞子 提交于 2019-12-24 23:47:48

问题


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); }


来源:https://stackoverflow.com/questions/4920530/typecast-operator-overloading-problem

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!