如何超载5 + obj [英] how to over load 5+obj

查看:118
本文介绍了如何超载5 + obj的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  #include   <   iostream.h  >  
#include < conio.h >
class oo {
int l; public
oo():l( 9 ){}
void operator +( int j)
{
l = l + j;
}
oo operator +(oo k)
{l + = k.l;
return oo;
}
void d(){cout& lt;& lt; l;}
};

main()
{
oo s;
s + 5; // 正常工作
s.d(); // 正常工作
5 + s; // nolw我想这样做吗?< b>< / b>
SD();
getch();
}<

解决方案

为了让编译器解析表达式

  5  + s; 



你必须提供一种将对象转换为int的方法。这可以通过重载完成

  int   operator ()()



是演员操作符。关注谢尔盖的链接,你将学习如何做到这一点。


在你的课堂外声明所需的操作符,如下所示:

  int  operator +( int  i,oo& o){
返回 o + i;
}



P.S。:我会将第二个参数声明为const,但这需要您现有的运算符声明为const正确。如果您的运营商实施与预期一致,它也会有所帮助,i。即他们不应该修改底层对象,除非你重写 operator + =()


不清楚。请参阅:

http://en.cppreference.com/w/cpp/language /运营商 [ ^ ],

http://www.tutorialspoint.com/cplusplus/cpp_overloading.htm [< a href =http://www.tutorialspoint.com/cplusplus/cpp_overloading.htmtarget =_ blanktitle =New Window> ^ ],

http://en.wikipedia.org/wiki/Operator_overloading [ ^ ]。



-SA

#include <iostream.h>
#include <conio.h>
class oo{
     int l; public:
     oo():l(9){} 
      void operator +(int j)
      { 
l=l+j;
           }
      oo operator +(oo k)
      {  l+=k.l;
          return oo;
           }
   void d(){ cout &lt;&lt; l;}
      };

main()
{
oo s;
s+5; // working fine
s.d(); // working fine
5+s; // nolw i  want to do it ?<b></b>
s.d();
getch();
}<

解决方案

In order to have the compiler resolve the expression

5 + s;


you have to provide a way to convert the object s into an int. That can be done by overloading

int operator()()


that is the cast operator. Follow Sergey's links and you will learn how to do that.


Declare the required operator outside your class, like this:

int operator+(int i, oo& o) {
   return o+i;
}


P.S.: I would have declared that second argument as const, but that would require your existing operator declarations to be const correct. It would also help if your operator implementations were consistent with expectations, i. e. they shouldn't modify the underlying object, unless you're overriding operator+=().


Not clear. Please see:
http://en.cppreference.com/w/cpp/language/operators[^],
http://www.tutorialspoint.com/cplusplus/cpp_overloading.htm[^],
http://en.wikipedia.org/wiki/Operator_overloading[^].

—SA


这篇关于如何超载5 + obj的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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