找回密码
 注册
搜索
热搜: 回贴
  • 前程无忧官网首页 有什么好的平台可以
  • 最新的销售平台 互联网营销的平台有哪
  • 制作网页的基本流程 网页制作和网页设
  • 【帝国CMS】输出带序号的列表(数字排
  • 网站建设公司 三一,中联,极东泵车的
  • 织梦 建站 织梦网站模版后台怎么更改
  • 云服务官网 哪些网站有免费的简历模板
  • 如何建网站要什么条件 建网站要用什么
  • 吉林市移动公司电话 吉林省退休人员网
  • 设计类毕业论文 网站设计与实现毕业论
查看: 1503|回复: 7

类类型转换

[复制链接]
发表于 2009-11-3 03:14:24 | 显示全部楼层 |阅读模式 IP:江苏扬州
#include <iostream>
using namespace std;
class Complex
{public:
Complex(double r=0,double i=0):real(r),imag(i){}
Complex(int r){real=r;imag=0;}
friend Complex operator+(Complex a,Complex b);/*friend Complex operator+(Complex &a,Complex &b);这样写为什么会出错啊*/
void display();
private:
double real;
double imag;
};
Complex operator+(Complex a,Complex b)
{Complex c;
c.real=a.real+b.real;
c.imag=a.imag+b.imag;
return c;}
void Complex::display()
{cout<<"("<<real<<","<<imag<<"i)"<<endl;}
int main()
{Complex c1(1.0,2.4),c2(2.3,4),c3;
c3=6+c1; /*如果我这里改成c3=c1+c2就不会错为什么呢*/
cout<<"c1+c2=";c3.display();
return 0;
}
发表于 2009-11-3 03:14:26 | 显示全部楼层 IP:江苏扬州
#include <iostream>
using namespace std;
class Complex
{public:
    Complex(double r=0,double i=0):real(r),imag(i){}
    Complex(int r){real=r;imag=0;}
  friend Complex operator+(const Complex &a, const Complex &b);
    void display();
private:
    double real;
    double imag;
};

Complex operator+(const Complex &a, const Complex &b)
{
Complex c;
c.real=a.real+b.real;
c.imag=a.imag+b.imag;
return c;
}

void Complex::display()
{cout<<"("<<real<<","<<imag<<"i)"<<endl;}

int main()
{Complex c1(1.0,2.4),c2(2.3,4),c3;
c3=6+c1;
cout<<"c1+c2=";
c3.display();
return 0;
}
回复

使用道具 举报

发表于 2009-11-3 03:14:28 | 显示全部楼层 IP:江苏扬州
friend Complex operator+(const Complex &a, const Complex &b);
为什么用const
回复

使用道具 举报

发表于 2009-11-3 03:14:29 | 显示全部楼层 IP:江苏扬州
你说哪种对?

operator +(6, c1);
operator +((Complex(6), c1);

编译器明显要处理能第二种才会编译通过,第一种则类型不匹配.
只有const修饰的对象才能自动调用Complex(double x)构造函数
回复

使用道具 举报

发表于 2009-11-3 03:14:30 | 显示全部楼层 IP:江苏扬州
只有const修饰的对象才能自动调用Complex(double x)构造函数
为什么 我还是不大明白,const不是定义常量的吗?这样一来const Complex &a, const Complex &b不变成两个常对象了吗?有什么意义呢?
回复

使用道具 举报

发表于 2009-11-3 03:14:31 | 显示全部楼层 IP:江苏扬州
c3=6+c1;
编译器这行认为
c3 = operator + (complex(6), c1);
这里complex(6)会生成一个临时对象,而临时对象都是右键.而右键都是const

当形参是指针或引用的时候,如果实参是个const.那么形参也必须是const
回复

使用道具 举报

发表于 2009-11-3 03:14:32 | 显示全部楼层 IP:江苏扬州
当形参是指针或引用的时候,如果实参是个const.那么形参也必须是const

支持~!
回复

使用道具 举报

发表于 2009-11-3 03:14:33 | 显示全部楼层 IP:江苏扬州
这里complex(6)会生成一个临时对象,而临时对象都是右键.而右键都是const
。。。。
我理解是根据变量定义的理解
变量定义是有名称,可寻址,可修改
这里因为没有名字,不能寻址,不可修改
所以是常量
又因为这里用到数据类型
所以只能是const
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

QQ|小黑屋|最新主题|手机版|微赢网络技术论坛 ( 苏ICP备08020429号 )

GMT+8, 2024-9-30 13:27 , Processed in 0.211494 second(s), 11 queries , Gzip On, MemCache On.

Powered by Discuz! X3.5

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表