【问题标题】:Should child class override the constructors if they have identical parameter as the parent class?如果子类具有与父类相同的参数,子类是否应该覆盖构造函数?
【发布时间】:2020-09-20 13:48:57
【问题描述】:

我正在使用 VC++。

我定义了一个父类:

class A
{
   A();
   A(int a);

   virtual ~A();

   virtual void DoSomething();
}

然后定义一个子类:

class B: public A
{
   virtual void DoSomething();
}

在 B 类中,只引入了新版本的 DoSomething。其他所有函数,包括构造函数和析构函数都和A一样。

例如,以下两个构造函数对 B 都可以:

B MyB;
B MyB(1);

在这种情况下,我需要创建构造函数 B() 和 B(int a) 吗?

我尝试忽略B()中的构造函数和析构函数,希望它可以从A继承,但是编译器会报错:

B MyB(1);

【问题讨论】:

  • 另外几点说明,virtual 关键字仅在最顶层的基类中需要。而且我真的建议您在覆盖函数时使用特殊标识符override(如class B : public A { public: void DoSomething() override; };
  • @Someprogrammerdude,抱歉我的错误,我已修复错误。 B 继承自 A。

标签: c++ class inheritance visual-c++ constructor


【解决方案1】:

默认构造函数B::B()implicitly-defined,而B::B(int) 不是。您可以显式定义一个,或将using 应用于inheriting constructor(C++11 起)。

如果 using-declaration 引用了正在定义的类的直接基类的构造函数(例如using Base::Base;),则该基类的所有构造函数(忽略成员访问)都对重载可见初始化派生类时的分辨率。

class B : public A
{
   using A::A;
   virtual void DoSomething();
}

【讨论】:

  • 抱歉,但使用 Base::Base 似乎不适用于 Visual C++ 2008?
  • @alancc 抱歉,这是 C++11 功能。 VC 2008 肯定不支持它。我认为您必须自己定义B::B(int)
猜你喜欢
  • 1970-01-01
  • 2021-01-17
  • 1970-01-01
  • 1970-01-01
  • 2017-02-03
  • 1970-01-01
  • 2013-10-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多