gpt4 book ai didi

C++虚类方法

转载 作者:行者123 更新时间:2023-11-27 22:48:43 24 4
gpt4 key购买 nike

假设我有一个 C++ 父类(super class) A,它有一个虚方法。如果我想在我的 B 类上重写它并仍然保持虚拟,是否建议在 B 类上保留 virtual 关键字?我可以忽略它吗,因为我已经说过该方法在父类(super class)上是虚拟的?

例如,执行以下操作的正确方法是什么。

方法一:

class A{ 
public:
virtual void hello(){
std::cout << "Hello World!" << std::endl;
};
};
class B: public A{
public:
virtual void hello() override{
std::cout << "Hello Sun!" << std::endl;
};

};
class C: public B{
public:
virtual void hello() override{
std::cout << "Hello Moon!" << std::endl;
};

};

或者仅在第一个类上将函数声明为虚函数。

方法B:

class A{ 
public:
virtual void hello(){
std::cout << "Hello World!" << std::endl;
};
};
class B: public A{
public:
void hello() override{
std::cout << "Hello Sun!" << std::endl;
};

};
class C: public B{
public:
void hello() override{
std::cout << "Hello Moon!" << std::endl;
};

};

我想在所有情况下都使用延迟出价。所以我需要 hello() 方法在三个类中是虚拟的。这两种方法都适用于 CodeBlocks,但我不知道什么是最好的方法,即使它们之间有任何区别。

最佳答案

virtual对于BC来说是多余的,效果是完全一样的。重要的是始终用 override1 标记您的方法(如果它们打算覆盖虚拟方法)。虽然这不是绝对必要的,但这是一个很好的做法。您在这两个示例中都正确地做到了这一点。

相关标准语:

n4140

§ 10.3 [class.virtual] / 2

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, cv-qualification, and refqualifier (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.


1 override 作为说明符自 C++11 起可用。

关于C++虚类方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40094929/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com