【发布时间】:2013-02-26 23:38:06
【问题描述】:
基类明确声明该方法是非虚拟的。 它适用于 Visual Studio 2008、2010 和 2012 以及 whatever compiler ideone uses (gcc 4.7+ ?)。
#include <iostream>
class sayhi
{
public:
void hi(){std::cout<<"hello"<<std::endl;}
};
class greet: public sayhi
{
public:
virtual void hi(){std::cout<<"hello world"<<std::endl;}
};
int main()
{
greet noob;
noob.hi(); //Prints hello world
return 0;
}
这也有效 - 该方法在基类中是私有且非虚拟的:
#include <iostream>
class sayhi
{
private:
void hi(){std::cout<<"hello"<<std::endl;}
};
class greet: public sayhi
{
public:
virtual void hi(){std::cout<<"hello world"<<std::endl;}
};
int main()
{
greet noob;
noob.hi(); //Prints hello world
return 0;
}
我的问题是:
- 合法吗?
- 为什么有效?
【问题讨论】:
标签: c++ inheritance virtual-functions