自动类型转换之运算符重载

第二种自动类型转换的方法是运算符重载,其是形式是operator 目的类型();   这个函数通过在关键字operator后跟随想要转换到的类型的方法,将当前类型转换为希望的类型。这种形式的运算符重载是独特的,因为没有指定返回值类型,其返回值类型就是正在重载运算符的名字。

 1 #include<iostream>
 2 using namespace std;
 3 
 4 class Three{
 5     int i;
 6 public:
 7     Three(int ii=0) :i(ii){
 8 
 9     }
10 
11 };
12 
13 class Four{
14     int x;
15 public:
16     Four(int xx) :x(xx){
17         
18     }
19     operator Three()const{//重载的运算符,功能是把类Four的对象转换成Three的对象。
20         return Three(x);
21     }
22 };
23 
24 
25 void g(Three){
26 
27 }
28 
29 int main(){
30     Four four(1);
31     g(four);//调用类型转换运算符,operator Three()const {return Three(x);}
32     g(1);//调用类型转换构造函数Three(int ii=0)
33 }

在自动类型转换技术中,构造函数技术是目的类执行转换,然而使用运算符技术,是源类执行转换。构造函数技术有一个缺陷就是无法从用户自定义的类型转换到内置类型,从用户自定义类型到内置类型的转换只有运算符重载可能做到。

原文地址:https://www.cnblogs.com/cplinux/p/5659926.html