ca70a_c++_重载函数_实参类型转换

/*ca70a_c++_重载函数_实参类型转换
转换等级,详见P290

编译选择哪个函数版本呢?
1.精确匹配
2.通过类型提升
3.通过标准转换
4.通过类类型转换
参数匹配和枚举类型
重载和const形参

void f(int *p) { cout << "f(int *p)" << endl; }
void f(const int *p) { cout << "f(const int *p)" << endl; }
//f(const int *p),*p指针指向const对象
//f(int *const p),*p const,表示指针是const,对象不是const.指向非const的对象
txwtech
*/

 1 /*ca70a_c++_重载函数_实参类型转换
 2 转换等级,详见P290
 3 1.精确匹配
 4 2.通过类型提升
 5 3.通过标准转换
 6 4.通过类类型转换
 7 参数匹配和枚举类型
 8 重载和const形参
 9 
10 void f(int *p) { cout << "f(int *p)" << endl; }
11 void f(const int *p) { cout << "f(const int *p)" << endl; }
12 //f(const int *p),*p指针指向const对象
13 //f(int *const p),*p const,表示指针是const,对象不是const.指向非const的对象
14 txwtech
15 */
16 
17 #include <iostream>
18 using namespace std;
19 
20 class Account
21 {
22 public:
23     Account() {}
24     Account(int x) :num(x) {}//构造函数,num=x;
25 public:
26     int num;
27 
28 };
29 enum Tokens
30 {
31     INLINE=128,
32     VIRTUAL=129
33 };
34 void lookup(Account &x) { cout << "lookup(Account &x)" << endl; }
35 void lookup(const Account& y) { cout << "lookup(const Account& y)" << endl; };
36 
37 void ff(Tokens t) { cout << "ff(Tokens t)" << endl; }
38 void ff(int x) { cout << "ff(int x):"<<x << endl; }
39 void ff(short y) { cout << "ff(short y)" << endl; }
40 //void manip(long x) { cout << "manip(long x)" << endl; }//long与float平级,产生了二义性。
41 void manip(float y) { cout << "manip(float y)" << endl; }
42 void newf(unsigned char x) { cout << "newf(unsigned char x) " << endl; }
43 void newf(int y) { cout << "newf(int y) " << endl; }
44 
45 void f(int *p) { cout << "f(int *p)" << endl; }
46 void f(const int *p) { cout << "f(const int *p)" << endl; }
47 //f(const int *p),*p指针指向const对象
48 //f(int *const p),*p const,表示指针是const,对象不是const.指向非const的对象
49 //f(int *p)与f(int *const p)是一个意思,不允许都出现。
50 int main()
51 {
52     ff('a');//char优先转换为int,int级别高,a转int就是97
53     manip(3.14);//long与float平级,产生了二义性。
54     ff(128);//128与int是精确匹配。
55     //调用枚举
56     Tokens ourTok = INLINE;
57     ff(ourTok);//调用枚举
58     //枚举成员调用
59     ff(INLINE);//也可以
60 
61     unsigned char uc = 129;
62     newf(VIRTUAL);//调用newf(int y),枚举成员是int类型的
63     newf(uc);
64 
65     const Account a(0);
66     Account b;
67     lookup(a);//调用lookup(const Account& y)
68     lookup(b);//调用lookup(Account &x)
69 
70     int m = 5, n = 6;
71     int *p = &m;
72     const int *p2 = &n;
73     f(p);
74     f(p2);
75     return 0;
76 }

 

原文链接: https://www.cnblogs.com/txwtech/p/12287933.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍;

也有高质量的技术群,里面有嵌入式、搜广推等BAT大佬

    ca70a_c++_重载函数_实参类型转换

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/328083

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年3月1日 下午4:32
下一篇 2023年3月1日 下午4:33

相关推荐