简化运算符重载. [英] Simplifying Operator Overloading .

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

问题描述



我有一个名为Yup的类,它有一个int类型的数据成员(称为number).
我已经超载了cout和+运算符.

cout<< object(type Yup)==>打印号码.
object1 + object2将2个对象的数量相加.

我主要是

是的t(23),t1(27);

当我这样做时:Yup t2 = t + t1; cout< t2< endl; ==>我得到50;


当我这样做时:cout<((t + t1)<< endl; ==>我得到-87293 ...

我怎么能用一行写出来?
如何编译?


Hey

I have a class named Yup and it has one data member of type int(called number).
I have overloaded the cout and + operators.

cout<<object(type Yup)==> prints the number.
The object1+object2 adds the numbers of 2 objects.

In the main I have

Yup t(23),t1(27);

When I do this: Yup t2=t+t1; cout<<t2<<endl;==> I get 50;


When I do this: cout<<(t+t1)<<endl; ==> I get -87293...

How can i write it in one line?
How it is compiled?


ostream &operator<<( ostream &output, const Yup &num )
{
    output<<num.number;
    return output;
}

Yup &operator+(const Yup &tr1,const Yup &tr2 )
{
    Yup k(0);
    k.number=tr1.number+tr2.number;
    return k;
}

推荐答案

您的operator+ ^ ]返回对局部变量的引用.

删除引用:
Your operator+ overload[^] returns a reference to a local variable.

Remove the reference:
Yup operator+( const Yup &tr1,const Yup &tr2 )


您可能未正确定义operator +.它应该返回包含结果的类的对象.如有疑问,请使用问题的改进问题"按钮显示代码.
You probably have defined operator+ incorrectly. It should return an object of your class that contains the result. If in doubt, show your code by using the "Improve question" button on your question.


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

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