是“虚拟”吗? C++ 中的基类中的关键字可选吗?

发布于 2024-12-01 21:40:26 字数 647 浏览 2 评论 0原文

我试图理解 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

夜声 2024-12-08 21:40:27

您没有使用多态性。多态行为仅影响对基类的指针和引用,如下所示:

class A; class B1 : A; class B2 : A;

B1 x;
B2 y;
A  z;

A & a1 = x;  // static type A&, dynamic type B1&
A & a2 = y;  // static type A&, dynamic type B2&
A & a3 = z;  // static and dynamic type A&

现在访问 a1a2a3 的成员函数受到多态性的影响,并且虚拟调度。

但是,您必须将继承层次结构顶部的第一个函数声明为虚拟,即在 A 中!在您的示例中,如果没有virtual,就没有多态性,并且您始终调用对象的相应静态类型的成员函数。要测试这一点,请添加另外几行:

a & bref = b_obj;
bref.say_hi();       // call b::say_hi() if virtual, a::say_hi if not
bref.a::say_hi();    // always call a::say_hi()

You aren't using polymorphism. Polymorphic behaviour only affects pointers and references to base classes, like so:

class A; class B1 : A; class B2 : A;

B1 x;
B2 y;
A  z;

A & a1 = x;  // static type A&, dynamic type B1&
A & a2 = y;  // static type A&, dynamic type B2&
A & a3 = z;  // static and dynamic type A&

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, without virtual, 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:

a & bref = b_obj;
bref.say_hi();       // call b::say_hi() if virtual, a::say_hi if not
bref.a::say_hi();    // always call a::say_hi()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文