【问题标题】:Inherited constructor and stl containers error [duplicate]继承的构造函数和 stl 容器错误 [重复]
【发布时间】:2015-05-21 15:31:07
【问题描述】:

我在玩继承的构造函数,但是当我尝试从 std::string 继承时,我很难理解为什么 gcc 会抱怨。

我知道这不是最佳做法,应该不惜一切代价避免它,所以在为此大喊大叫之前,我不会在任何地方实施它 :-) 这只是为了纯粹的好奇。

我也用一个简单的已定义类尝试了相同的场景,但我没有遇到同样的问题。

#include <string>
#include <vector>
#include <iostream>

using namespace std;

template <typename T>
struct Wrapper : public T
{
    using T::T;
};

struct A{
  A(int a) : _a(a) {} 
  int _a; 
};

int main()
{
   Wrapper<string> s("asd"); //compiles
   string a = "aaa";
   Wrapper<string> s2(a); //does not compile

   Wrapper<A> a(1);
   int temp = 1;
   Wrapper<A> b(temp);
}

实际错误的摘录:

main.cpp:25:24: 错误:没有匹配函数调用'Wrapper&lt;std::basic_string&lt;char&gt; &gt;::Wrapper(std::string&amp;)'

Wrapper<string> s2(a);

【问题讨论】:

    标签: c++ c++11 inheritance stl inherited-constructors


    【解决方案1】:

    复制构造函数不被继承。你需要声明一个构造函数来获取T

    Wrapper(T const& t):
        T(t){}
    

    也可能是非const 和移动变体:

    Wrapper(T& t):
        T(t){}
    Wrapper(T&& t):
        T(std::move(t)){}
    

    【讨论】:

      猜你喜欢
      • 2016-11-01
      • 2014-01-10
      • 2014-08-21
      • 1970-01-01
      • 2017-12-05
      • 2021-06-30
      • 2014-11-22
      • 2015-05-25
      相关资源
      最近更新 更多