c++ const指针与函数调用

  在我的博客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()。

转自: https://blog.csdn.net/caoyan_12727/article/details/52493555

猜你喜欢

转载自blog.csdn.net/jctian000/article/details/81663333