为什么允许覆盖非虚函数?
Why is it allowed to overide non-virtual function?
我正在试验 C++ 中的继承。
struct A {
virtual void foo(){ std::cout << "foo()" << std::endl; }
void bar(){ std::cout << "bar()" << std::endl; }
};
struct B : A{
void foo(){ std::cout << "derived foo()" << std::endl; }
void bar(){ std::cout << "derived bar()" << std::endl; }
};
struct C : B {
void foo(){ std::cout << "derived derived foo()" << std::endl; }
void bar(){ std::cout << "derived derived bar()" << std::endl; }
};
int main()
{
B* b = new C();
b->foo(); //derived derived foo()
b->bar(); //derived bar()
}
因为函数 foo
在 struct B
中声明为非虚函数,所以我预计 B
的函数会被调用。但是 foo
是 C
中的哪一个。为什么?我更改了 B
中函数的 "virtual status"。为什么还是虚拟的?
一次虚拟永远虚拟。
由于 foo
在 A
中是虚拟的,因此在从 A
派生的所有 类 中都是虚拟的 - 无论他们是否获得 virtual
关键字.
foo()
在基础 class A
中被声明为虚函数,所以 foo()
在所有派生的 class 中也将是虚函数。
根据标准,10.3$2 虚函数 [class.virtual](我加粗)
If a virtual member function vf is declared in a class Base and in a
class Derived, derived directly or indirectly from Base, a member
function vf with the same name, parameter-type-list (8.3.5),
cv-qualification, and ref-qualifier (or absence of same) as Base::vf
is declared, then Derived::vf is also virtual (whether or not it is so
declared) and it overrides Base::vf.
上面提到的答案是有效的,但是我们可以使用 override
关键字吗,因为
The override special identifier means that the compiler will check the
base class(es) to see if there is a virtual function with this exact
signature. And if there is not, the compiler will indicate an error.
所以像这样的东西是 struct B
:
void bar() override
我正在试验 C++ 中的继承。
struct A {
virtual void foo(){ std::cout << "foo()" << std::endl; }
void bar(){ std::cout << "bar()" << std::endl; }
};
struct B : A{
void foo(){ std::cout << "derived foo()" << std::endl; }
void bar(){ std::cout << "derived bar()" << std::endl; }
};
struct C : B {
void foo(){ std::cout << "derived derived foo()" << std::endl; }
void bar(){ std::cout << "derived derived bar()" << std::endl; }
};
int main()
{
B* b = new C();
b->foo(); //derived derived foo()
b->bar(); //derived bar()
}
因为函数 foo
在 struct B
中声明为非虚函数,所以我预计 B
的函数会被调用。但是 foo
是 C
中的哪一个。为什么?我更改了 B
中函数的 "virtual status"。为什么还是虚拟的?
一次虚拟永远虚拟。
由于 foo
在 A
中是虚拟的,因此在从 A
派生的所有 类 中都是虚拟的 - 无论他们是否获得 virtual
关键字.
foo()
在基础 class A
中被声明为虚函数,所以 foo()
在所有派生的 class 中也将是虚函数。
根据标准,10.3$2 虚函数 [class.virtual](我加粗)
If a virtual member function vf is declared in a class Base and in a class Derived, derived directly or indirectly from Base, a member function vf with the same name, parameter-type-list (8.3.5), cv-qualification, and ref-qualifier (or absence of same) as Base::vf is declared, then Derived::vf is also virtual (whether or not it is so declared) and it overrides Base::vf.
上面提到的答案是有效的,但是我们可以使用 override
关键字吗,因为
The override special identifier means that the compiler will check the
base class(es) to see if there is a virtual function with this exact
signature. And if there is not, the compiler will indicate an error.
所以像这样的东西是 struct B
:
void bar() override