如何实现这样的类(表达能力有限,但看过你就会明白)?

cycker 2002-05-06 10:49:46
myclass my(2);
int x=my;
//这时x=2
int xx=1;
xx=xx+my;
这时xx=3
好象很难实现。
...全文
40 7 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
Linux2001 2002-05-06
  • 打赏
  • 举报
回复
重载运算符
z_sky 2002-05-06
  • 打赏
  • 举报
回复
重载类的操作符 = 和 +
FlyingHero 2002-05-06
  • 打赏
  • 举报
回复
class myclass
{
public:
myclass(int i){m_value = i;}
operator int(){return m_value;}
private:
int m_value;
}
prototype 2002-05-06
  • 打赏
  • 举报
回复
use conversion operator.
prototype 2002-05-06
  • 打赏
  • 举报
回复
我不用重载operater +也可以实现加法,为什么?
because of the conversion operator ('operator int()'), 'my1', 'my2' and 'my3' were converted to 'int' implicitly.
diaopeng 2002-05-06
  • 打赏
  • 举报
回复
没什么,用类型转换吧,将用户定义的类型转换成基本类型就可以使用系统预定义的+、-,*、/等的运算
cycker 2002-05-06
  • 打赏
  • 举报
回复
#include <iostream.h>
#include <stdio.h>

class myclass
{
public:

myclass(int i){m_value = i;}
operator int(){return m_value;}
private:
int m_value;
} ;


int main(int argc, char *argv[])
{
myclass my(0);
int x(my);
myclass my2(1);
x+=my2;
myclass my3(3);
x=my+my2+my3;

cout<<x<<endl;
getchar();
return 0;
}

奇怪的是,我不用重载operater +也可以实现加法,为什么?

70,023

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧