C++隐式类类型转换(转)

《C++ Primer》

可以用单个实参来调用的构造函数定义了从形参类型到该类类型的一个隐式转换。

原文网址:
浅谈C++类(4)--隐式类类型转换

 1 #include <string>
 2 #include <iostream>
 3 using namespace std;
 4 class Fruit               //定义一个类,名字叫Fruit
 5 {
 6  string name;     //定义一个name成员           
 7  string colour;   //定义一个colour成员
 8  
 9 public:
10  bool isSame(const Fruit &otherFruit)   //期待的形参是另一个Fruit类对象,测试是否同名
11  {
12   return name == otherFruit.name;
13  }
14  void print()              //定义一个输出名字的成员print()
15  {
16   cout<<colour<<" "<<name<<endl;
17  }
18  Fruit(const string &nst,const string &cst = "green"):name(nst),colour(cst){}  //构造函数
19  
20  Fruit(){}
21 };
22 
23 int main()
24 {
25  Fruit apple("apple");
26  Fruit orange("orange");
27  cout<<"apple = orange ?: "<<apple.isSame(orange)<<endl;  //没有问题,肯定不同
28  cout<<"apple = /"apple/" ?:"<<apple.isSame(string("apple")); //用一个string做形参?
29  
30     return 0;
31 }

你会发现最后的使用上,我们用一个string类型作一个期待Fruit类形参的函数的参数,结果竟然得出了是true(1),不要感到奇怪,这就是我现在要讲的东西,隐式类类型转换:“可以用单个实参来调用的构造函数定义了从形参类型到该类型的一个隐式转换。”(C++ Primer)首先要单个实参,你可以把构造函数colour的默认实参去掉,也就是定义一个对象必须要两个参数的时候,文件编译不能通过。然后满足这个条件后,系统就知道怎么转换了,不过这里比较严格:)以前我们构造对象的时候Fruit apple("apple")其实也已经有了一个转换,从const char *的C字符串格式,转为string,在这里,你再apple.isSame("apple")的话,蠢系统不懂得帮你转换两次,所以你必须要用string()来先强制转换,然后系统才知道帮你从string隐式转换为Fruit,当然其实你自己也可以帮他完成。cout<<"apple = /"apple/" ?:"<<apple.isSame(Fruit("apple"));这样。参考例子1.2 :

1 Fruit apple = Fruit("apple");  //定义一个Fruit类对象apple。

 

也就是这样转换的。不过这就叫显式转换了,我们不标出来,系统帮我们完成的,叫隐式的贝。这里要说的是,假如你显示转换就可以不管有多少参数了,比如在前面提到的必须需要两个参数的构造函数时的例子。

例4.1:

 1 #include <string>
 2 #include <iostream>
 3 using namespace std;
 4 class Fruit               //定义一个类,名字叫Fruit
 5 {
 6  string name;     //定义一个name成员           
 7  string colour;   //定义一个colour成员
 8  
 9 public:
10  bool isSame(const Fruit &otherFruit)   //期待的形参是另一个Fruit类对象,测试是否同名
11  {
12   return name == otherFruit.name;
13  }
14  void print()              //定义一个输出名字的成员print()
15  {
16   cout<<colour<<" "<<name<<endl;
17  }
18  Fruit(const string &nst,const string &cst):name(nst),colour(cst){}  //构造函数
19  
20  Fruit(){}
21 };
22 
23 int main()
24 {
25  Fruit apple("apple","green");
26  Fruit orange("orange","yellow");
27  cout<<"apple = orange ?: "<<apple.isSame(orange)<<endl;  //没有问题,肯定不同
28  cout<<"apple = /"apple/" ?:"<<apple.isSame(Fruit("apple","green")); //显式转换 
29     return 0;
30 }

 好了,懂了,感谢原文作者。

posted @ 2012-10-29 19:58  leealways87  阅读(334)  评论(0编辑  收藏  举报