是“虚拟”吗? C++ 中的基类中的关键字可选吗?
我试图理解 C++ 中“virtual”关键字的功能 - 考虑这个例子:
#ifdef USE_VIRTUAL
struct a {
virtual void say_hi() { std::cout << "hello from a" << std::endl; }
};
#else
struct a {
void say_hi() { std::cout << "hello from a" << std::endl; }
};
#endif
struct b : public a {
void say_hi() { std::cout << "hello from b" << std::endl; }
};
int main( int argc, char** argc )
{
a a_obj;
b b_obj;
a_obj.say_hi();
b_obj.say_hi();
}
该程序输出:
hello from a
hello from b
无论 a::say_hi 是否被声明为 virtual 。既然即使 say_hi 没有声明为 virtual,该函数也会被正确覆盖,那么将其声明为 virtual 的函数是什么?
I'm trying to understand the function of the "virtual" keyword in C++ - consider this example:
#ifdef USE_VIRTUAL
struct a {
virtual void say_hi() { std::cout << "hello from a" << std::endl; }
};
#else
struct a {
void say_hi() { std::cout << "hello from a" << std::endl; }
};
#endif
struct b : public a {
void say_hi() { std::cout << "hello from b" << std::endl; }
};
int main( int argc, char** argc )
{
a a_obj;
b b_obj;
a_obj.say_hi();
b_obj.say_hi();
}
This program outputs:
hello from a
hello from b
regardless of whether or not a::say_hi is declared as virtual or not. Since the function gets correctly overridden even when say_hi is not declared virtual, then what is the function of declaring it as virtual?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您没有使用多态性。多态行为仅影响对基类的指针和引用,如下所示:
现在访问
a1
、a2
、a3
的成员函数受到多态性的影响,并且虚拟调度。但是,您必须将继承层次结构顶部的第一个函数声明为虚拟,即在
A
中!在您的示例中,如果没有virtual
,就没有多态性,并且您始终调用对象的相应静态类型的成员函数。要测试这一点,请添加另外几行:You aren't using polymorphism. Polymorphic behaviour only affects pointers and references to base classes, like so:
Now accessing member functions of
a1
,a2
,a3
is subject to polymorphism and virtual dispatch.However, you must declare the first function at the top of the inheritance hierarchy virtual, i.e. in
A
! In your example, withoutvirtual
, there's no polymorphism and you always call the member function of the corresponding static type of the object. To test this, add another few lines: