找不到基的构造函数

Constructor from base not found

本文关键字:构造函数 找不到      更新时间:2023-10-16
#include <string_view>
class str_ref : public std::string_view
{
public:
  using std::string_view::string_view;
};
int main()
{
  std::string_view sv;
  str_ref sr("", 0);
  str_ref sr2(sv); // error C2664: 'str_ref::str_ref(const str_ref &)': cannot convert argument 1 from 'std::string_view' to 'const char *const '
}

为什么在这里找不到 (string_view( 的构造函数?不应该使用 using 语句导入此构造函数吗?正在找到(常量字符*,size_t(构造函数。我正在使用VS2017。

不应该使用 using 语句导入此构造函数吗?

它是正确导入的,但您必须自己在派生类中定义该构造器。
编译器不会为派生类自动生成类似的构造函数:

#include <string_view>
class str_ref : public std::string_view
{
public:
  using std::string_view::string_view;
  str_ref(const std::string_view& sv) : std::string_view(sv) {} // <<<<
};
int main()
{
  std::string_view sv;
  str_ref sr("", 0);
  str_ref sr2(sv);
}

观看现场演示