const函数重载
来源:互联网 发布:kindle 购买 知乎 编辑:程序博客网 时间:2024/05/21 17:12
C++允许类的成员函数基于const重载。
#include<iostream>using namespace std; class Test{protected: int x;public: Test (int i):x(i) { } void fun() const { cout << "fun() const called " << endl; } void fun() { cout << "fun() called " << endl; }}; int main(){ Test t1 (10); const Test t2 (20); t1.fun(); t2.fun(); return 0;}
输出:
fun() calledfun() const called我们可以看到非const对象调用的是非const成员函数,const对象调用的是const成员函数。
下面两个例子很有意思,重载不是类的成员函数,而是普通函数的重载,
程序1
#include<iostream>using namespace std; void fun(const int i){ cout << "fun(const int) called ";}void fun(int i){ cout << "fun(int ) called " ;}int main(){ const int i = 10; fun(i); return 0;}
输出:
编译错误!
error C2084: 函数“void fun(const int)”已有主体
error C3861: “fun”: 找不到标识符
#include<iostream>using namespace std; void fun(char *a){ cout << "non-const fun() " << a;} void fun(const char *a){ cout << "const fun() " << a;} int main(){ const char *ptr = "CSDN"; fun(ptr); return 0;}
输出:
const fun() CSDN
0 0
- const函数重载
- 函数重载之const
- const函数重载
- const与重载函数
- const函数重载
- 函数重载之const
- 函数重载之const
- const 成员函数重载
- const函数重载
- const 和 非const函数重载
- const 和非 const 函数重载
- const 和 非const函数重载
- const&volatile 与函数重载
- const可以使得函数重载
- C++ 成员函数 const 重载
- C++函数重载和const
- const 参数重载与const 成员函数重载
- 顶层const、底层const、函数重载与const形参
- 常用Git命令
- phpmyadmin 出现The mbstring extension is missing
- 判断JavaScript对象是否存在的10个方法
- 新手装修不必犯愁 教你五招筛选出满意的设计师 - 中国度居网株洲站 - 株洲
- Java虚拟机3——垃圾回收算法
- const函数重载
- 关于Ubuntu源列表的更改 - source list
- 2014年最新燕十八老师PHP视频教程10K月薪高性能架构班
- el表达式截取字符串
- [sicily]1151. 魔板[Special judge]
- Oracle日志文件的状态current/active/inactive/unused
- yii 缓存机制
- 《Android编程权威指南》关于activity的总结
- 人缘好交通费