C++中的基类中的"virtual"关键字是可选的吗?

Chr*_*Vig 3 c++ virtual keyword

我试图理解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();
}
Run Code Online (Sandbox Code Playgroud)

该计划输出:

hello from a
hello from b
Run Code Online (Sandbox Code Playgroud)

无论:: say_hi是否被声明为虚拟.由于即使say_hi未声明为虚拟,函数也会被正确覆盖,那么将其声明为虚拟的功能是什么?

Ker*_* SB 6

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

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&
Run Code Online (Sandbox Code Playgroud)

现在访问的成员函数a1,a2,a3是受多态性与虚拟调度.

但是,您必须在继承层次结构的顶部声明第一个函数virtual,即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()
Run Code Online (Sandbox Code Playgroud)