c++const指针与函数调用
来源:互联网 发布:嗨推淘宝客论坛 编辑:程序博客网 时间:2024/06/16 01:26
在我的博客http://blog.csdn.net/caoyan_12727/article/details/52064958中,已经讨论了动态绑定和静态绑定,以及在缺省参数情况下虚函数的绑定情况。一般情况下,我们
是用非const的基类指针指向派生类对象,如果通过该指针调用虚函数则发生的动态绑定,如果我们定义一个const指针,指向派生类的对象,如果派生类里定义了同名的虚函数和
const函数,会发生什么调用???
测试1:
#include<iostream>#include<vector>#include<map>#include<sstream>using namespace std;class A{public:virtual void f(){cout << "A::f()" << endl;}void f() const{cout << "A::f() const" << endl;}};class B : public A{public:void f(){cout << "B::f()" << endl;}void f() const{cout << "B::f() const" << endl;}};void g(const A* a){a->f();}int main(){B bb;A aa;A const*ptr = &aa;ptr->f();A *ptr1 = &aa;ptr1->f();//派生类B const*ptr2 = &bb;ptr2->f();B *ptr3 = &bb;ptr3->f();A* a = new B();a->f();A const*a1 = new B();a1->f();g(a);delete a;return 0;}结果:
测试2:
将类A进行修改:
class A{public:virtual void f(){cout << "A::f()" << endl;}virtual void f() const{cout << "A::f() const" << endl;}};结果:
可以看出:
(1)const指针智能调用类的const函数,如果用const指针调用非const函数将会报错,非const指针调用const函数编译器不会报错。
(2)const与虚函数并存的时候,const指针只能调用const函数,测试1中,由于const f()不是虚的,所以对const调用时静态绑定,调用的是基类的const函数。在测试2中将
const f()设置为虚函数时,由于派生类重写const f(),所以调用派生类的const f()。
0 0
- c++const指针与函数调用
- C/C++指针与const、数组、函数
- C++:const与指针
- 函数返回const指针与const引用。
- C语言const与指针
- linux C编程(五)函数指针与函数调用
- c/c++ 复习基础要点01-const指针、指针函数 函数指针、new/delete与malloc/free区别与联系
- C/C++ 指针 数组 const 函数
- const与const指针
- C语言调用函数指针
- 指针与函数、数组和Const
- const与函数、指针的搭配
- const与指针、成员函数、#define
- C++ this指针与const成员函数
- C语言中的const与指针
- c的指针与复杂变量---const
- C经典 const与指针解析
- C指针与const的那些事
- completer自动完成
- 搭建MVP框架要点记录
- 4步win7下简单FTP服务器搭建(试验成功)
- 作为技术面试官,我是怎样评价一个游戏开发人员的素质的
- js实现检测网络是否连接的功能
- c++const指针与函数调用
- Cordova项目中遇到的一个插件安装的问题
- viewpager setCurrentItem 过多出现卡顿 ANR 线程阻塞 页面无响应
- 【蒻爆了的NOIP系列--普及组初赛】(1)2010-2014问题求解
- ReferenceError: “alert” is not defined
- Remmarguts' Date(k短路问题)
- 7.4 E HDU 2895Edit distance
- java中异常 try,catch,finally在不同情况下的执行顺序
- 类加载器(class loader)