我有一个函数 X() 在基类中声明为 PURE VIRTUAL:
class Base
{
public:
virtual HRESULT X()=0; // Now it's pure virtual.
.......
};
class Derived_1 : public Base
{
HRESULT X()
{
// body of function X() ; full definition given here as per Derived_1's context. SHOULD WE MAKE THIS VIRTUAL?
}
..................
};
class Derived_2 :public Base
{
HRESULT X()
{
// body of function X() ; full definition given here Derived_2's context. SHOULD WE MAKE THIS VIRTUAL?
}
..................
};
如果我们的意图是使用基类指针一般地调用函数 X(),那么决定是调用 Derived_1 还是 Derived_2 的 X() 定义,那么是否有必要将 Derived 类中的 X() 设为 Virtual也。
Base * bPtr;
bPtr = new Derived_1(); OR bPtr = new Derived_2(); (Dynamic decision)
bPtr->X()
我觉得在Derived classes的定义中没有必要附加virtual关键字。我说得对吗?
提前致谢。
最佳答案
如果派生类中的函数签名(参数类型和返回值、标识符,如 const 和 virtual)与基类中的相同,则派生类中的函数将自动为虚函数。不管是虚拟的还是纯虚拟的。
因此在您的示例中,没有必要为派生类添加虚拟。
关于c++ - 在 C++ 中,当我们在基类中将一个函数设为纯虚函数时,那么在子类中再次将同一函数设为虚函数的必要性是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9874172/