class Base
{
public:
virtual void func() const
{
cout<<"This is constant base "<<endl;
}
};
class Derived : public Base
{
public:
virtual void func()
{
cout<<"This is non constant derived "<<endl;
}
};
int main()
{
Base *d = new Derived();
d->func();
delete d;
return 0;
}
爲什麼輸出打印出「這是恆定基數」。然而,如果我刪除基礎版本的func()中的const,它會打印出「This is non constant derived derived」虛擬功能常量vs虛擬功能非常量
d-> func()應該調用Derived版本,即使基礎func ?
可能的重複http://stackoverflow.com/questions/7504300,http://stackoverflow.com/questions/3827374和http://stackoverflow.com/questions/4152799。 – 2012-02-28 19:12:54
[虛函數是在基類中的常量,而不是在派生的常量]的可能重複(http://stackoverflow.com/questions/7504300/virtual-function-that-is-const-in-the-base- class-and-not-const-in-the-derived) – 2012-02-28 19:58:16