关于C++中const形参在派生时的理解。
这是微软一道笔试原题:
#include<iostream>
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()
{
A* a = new B();
a->f();
g(a);
delete a;
return 0;
}
输出是
B::f()
A::f() const
(为什么?应该怎么理解?)
去掉函数g中的const后
输出是
B::f()
B::f()
(这个我的理解是虚函数在继承过程中,可以由指向派生类的基类指针访问到派生类的对应”虚函数“)
但是加了个const结果就不一样了,应该如何解释呢?