【问题标题】:Why C++ Don't Use Parent Class Constructor? [duplicate]为什么 C++ 不使用父类构造函数? [复制]
【发布时间】:2015-02-05 06:18:19
【问题描述】:

我想知道为什么在 C++ 中不能将父类构造函数用于特定签名,以防派生类错过?

例如在下面的示例中,我无法用std::string 初始化dd 对象。

#include <iostream>


class Base
{
    int num;
    std::string s;
public:
    Base(int _num){ num = _num;}
    Base(std::string _s){ s = _s;}
};

class Derived : public Base {
public:
    Derived(int _num):Base(_num){}
};

int main()
{
    Base b(50);
    Derived d(50);
    Base bb("hell");
    Derived dd("hell"); // <<== Error
    return 0;
}

通过继承,我希望扩展一个类并且不会丢失以前的功能,但在这里我觉得丢失了一些。

在一个更实际的例子中,我创建了我的std::string 版本,但在某些情况下它的行为不像std::string

#include <string>
#include <iostream>


class MyString: public std::string {
public:
    void NewFeature(){/* new feature implementation*/}
};

int main()
{
    MyString s("initialization");   // <<== Error: I expect to initialize with "..."
    cout<<s;                        // <<== Error: I expect to print it like this.
    return 0;
}

有人可以解释一下吗?

【问题讨论】:

    标签: c++ inheritance constructor initialization


    【解决方案1】:

    如果你也想继承构造函数,你需要在你的代码中告诉编译器:

    class Derived : public Base {
      public:
        using Base::Base;  // <- Makes Base's constructors visible in Derived
    };
    

    至于“我为什么需要这样做?”:廉价的答案是:因为标准是这样说的。

    为什么会这样是猜测(如果你不问委员会成员自己的话)。他们很可能希望避免“令人惊讶”或“不直观”的代码行为。

    【讨论】:

    • 虽然using std::string::std::string不起作用,但我需要这个问题的why。为什么Inheritance 在这里闻起来。
    • @Emadpres 有关std::string 的工作语法,请参阅here。 (几乎是我在答案中写的。:))
    • 我真的很惊讶。他们在标准中编写了一个特殊情况,以使 using std::string::string 之类的东西起作用(回想一下,std::string 实际上是 std::basic_string 的特定专业化的 typedef ...)
    • 我认为我的编译器 (VS2012) 使用 pre-c++11 标准。谢谢你的回答。
    • @BaummitAugen cout&lt;&lt;s; 怎么样。我应该做一些其他工作以使其正常工作等等?
    【解决方案2】:

    我没有足够的代表来标记为重复,但Inheriting constructors 充分回答了这个问题。

    基本上,在 C++11 之前的标准中,不允许允许构造函数继承。 C++11 改变了这一点,您现在可以继承构造函数。

    【讨论】:

      猜你喜欢
      • 2013-06-08
      • 2015-04-24
      • 1970-01-01
      • 2011-09-07
      • 2012-02-28
      • 1970-01-01
      • 1970-01-01
      • 2021-02-18
      • 2014-01-14
      相关资源
      最近更新 更多