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 }
复制代码

 

posted @   txwtech  阅读(165)  评论(0编辑  收藏  举报
编辑推荐:
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示