c++ - 找不到基的构造函数

标签 c++ c++17 visual-studio-2017

<分区>

#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 语句导入吗?正在找到 (const char*, size_t) 构造函数。 我正在使用 VS2017。

最佳答案

Shouldn't this constructor be imported with the using statement?

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

#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);
}

参见 Live Demo

关于c++ - 找不到基的构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44201014/

相关文章:

c++ - C++ 中的多级继承 (CRTP)

c++ - 声明类变量后调用构造函数

templates - 如何查找具有默认值的可变数量 constexpr std::arrays 的 constexpr max

c# - C++ 17 中的 std::byte 是否等同于 C# 中的字节?

visual-studio - 如何从 Visual Studio 禁用 Perfwatson2.exe

c++ - 在 new 表达式中分配内存后是否评估初始值设定项?

c++ - gcc 6 是否支持使用 std::sample (c++17)?

visual-studio - Visual Studio 2017 选项 : Use Managed Compatibility Mode per project

c++ - 构建解决方案时使 Visual Studio 的 CMake 工具运行 INSTALL

c++ - 无法让复制文件工作