Chinaunix首页 | 论坛 | 博客
  • 博客访问: 481917
  • 博文数量: 72
  • 博客积分: 1851
  • 博客等级: 上尉
  • 技术积分: 1464
  • 用 户 组: 普通用户
  • 注册时间: 2010-09-16 17:50
文章分类

全部博文(72)

文章存档

2013年(1)

2012年(17)

2011年(51)

2010年(3)

分类: C/C++

2011-05-22 17:10:45


 C++中的类型转换主要有两种方法:

1.利用构造函数

2.采用运算符重载

构造函数主要采用类似于复制构造函数形式: dst-class-name(const src-class-name)

:

  1. #include <iostream>

  2. using namespace std;

  3. class A {

  4. int x;

  5. public:

  6.     A(int i):x(i){}

  7.     int getX()const{return x;}

  8. };

  9. class B{

  10. int y;

  11. public:

  12.     B(int i):y(i){}

  13.     B(const A &a) {y=a.getX();}

  14.     int getY(){return y;}

  15. };



  16. void f(B b)

  17. {

  18.     cout<<"B:"<<b.getY()<<endl;

  19. }



  20. int main()

  21. {

  22.     A a(1);

  23.     f(a);

  24.     return 0;

  25. }

编译运行结果如下:

  1. ./Automatic
  2. B:1

但是上面就只能是按值进行传递,而非引用或者按指针

如果防止编译器间接进行转换,可以在构造函数前加上关键字”explicit p { margin-bottom: 0.21cm; }(专门针对构造函数) ”.

  1. #include <iostream>

  2. using namespace std;



  3. class Three

  4. {

  5. int i;

  6. public:

  7.  Three(int ii=0,int=0):i(ii){}

  8.  int getI()const {return i;}

  9. };

  10. class Four

  11. {

  12.  int x;

  13. public:

  14.  Four(int xx):x(xx){}

  15.  operator Three()const {return Three(x);}

  16. };

  17. void g(Three t){cout<<"Three:"<<t.getI()<<endl;}



  18. int main()

  19. {

  20.  Four four(1);

  21.  g(four);

  22.  return 0;

  23. }

3.运算符重载的方式

为了很好的利用类型自动转换,最好将运算符重载设置为友元函数.

  1. #include <iostream>



  2. using namespace std;



  3. class Number {

  4. int i;

  5. public:

  6. Number(int ii=0):i(ii){}

  7. const Number operator+(const Number& n)const{

  8.     cout<<"operator +"<<endl;

  9.     return Number(i+n.i);

  10. }

  11. friend const Number operator-(const Number&,const Number&);

  12. };

  13. const Number operator-(const Number& n1,const Number& n2)

  14. {

  15.     cout <<"operator - "<<endl;

  16.     return Number(n1.i-n2.i);

  17. };

  18. int main()

  19. {

  20. Number a(47),b(11);

  21. a+b;

  22. a-b;

  23. 1-b;

  24. return 0;

  25. }

如果出现了多个类之间的自动类型转换,就会导致转换模糊不清而出现错误,写转换的时候一定要小心。

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