Chinaunix首页 | 论坛 | 博客
  • 博客访问: 608304
  • 博文数量: 72
  • 博客积分: 1177
  • 博客等级: 少尉
  • 技术积分: 856
  • 用 户 组: 普通用户
  • 注册时间: 2011-12-23 23:03
文章分类

全部博文(72)

文章存档

2015年(13)

2014年(5)

2013年(7)

2012年(39)

2011年(8)

分类: C/C++

2012-10-13 16:32:54

数据的类型转换有两种形式:1 隐式类型转换;2 显式类型装换;
C++中规定数据类型级别从高到低的次序是:double->float->long int->int->short、char
自定义类型和内部类型之间的转换:1 构造函数;2类类型转换函数;
构造函数完成类型转换,类内至少定义一个只带一个参数的构造函数,当进行类型转换时,系统会自动调用该构造函数。
不能利用构造函数把自定义类型的数据转换为系统预定义类型的数据,只能实现系统预定义类型向自定义类类型的转换。
类类型转换函数定义格式:
class 源类类名
{
operator 目的类型()
{
。。。。。
return 目的类型的数据;
}
}
使用类类型转换需要注意的问题:
1 类类型转换函数只能定义为一个类的成员函数,而不能定义为类的友元函数
2 类类型转换函数既没有参数,也不显式给出返回类型
3 类类型转换函数必须有“return 目的类型数据”的语句,即必须返回目的类型数据作为函数的返回值
 

点击(此处)折叠或打开

  1. #include<iostream.h>
  2. class Complex
  3. {
  4. private:
  5.     double real;
  6.     double imag;
  7. public:
  8.     Complex(double x=0,double y=0);
  9.     operator float();
  10.     void print();
  11. };

  12. Complex::Complex(double x,double y)
  13. {
  14.     real=x;
  15.     imag=y;
  16. }

  17. Complex::operator float()
  18. {
  19.     return float(real);
  20. }

  21. void Complex::print()
  22. {
  23.     cout<<real<<","<<imag<<endl;
  24. }

  25. void main()
  26. {
  27.     Complex a(4.3,5.2);
  28.     Complex b(4.3,5.2);
  29.     a.print();
  30.     cout<<float(a)*0.5<<endl;
  31.     Complex c=a+b;
  32.     c.print();
  33. }

阅读(2127) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~