Typecast运算符重载问题 [英] Typecast operator overloading problem

查看:142
本文介绍了Typecast运算符重载问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我有两个类A和B,这样对于两个对象a和b,我想要能够:

A a;

B b;

a = b;

b = a;

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

但是当我尝试编译这个代码时,gcc会抛出错误:

错误:'B'之前的期望类型说明符

表示行: )const {return B(pVarA);}

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

我的猜测是,这是由于鸡和鸡蛋的问题,在A类之后。

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

有没有办法规避这种情况,同时仍然使用重载的typecast操作符。如果没有,那么什么可能是实现我的目标的最佳方式。

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.

推荐答案

尝试向前声明,然后提供实际的函数定义:

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

这篇关于Typecast运算符重载问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆