虚函数中指针变量和引用变量用法糊涂了?!

来源:百度知道 编辑:UC知道 时间:2024/05/19 00:23:07
class Base
{
public:
virtual int f(){ return 3;}
};
class Child : public Base
{
public:
int f(){ return 4;}
}
int main(int arg, char **args)
{
Child c1;
Base b1 = c1;
cout << b1.f() << endl; ---输出3
cout << c1.f() << endl; ---输出4
/*********************************/
Child *c2 = new Child;
Base *b2 = c2;
cout << b2->f() << endl; ---输出4
cout << c2->f() << endl; ---输出4
}

为什么引用变量没有实现override,指针变量缺能实现呢?!

第一个不是引用啊!b1.f()调用的就是基类的f(),因为当Base b1 = c1; 时,调用了基类的考贝构造函数创建了一个新的对象b1,所以。。。

而第二种b2只是一个指针,它指向的是子类的对象c2,所以,程序实现了多态性,所以。。。