小编San*_*lín的帖子

无法围绕 std::string 创建仅产生“语法糖”的包装器

我知道 std::string不是为继承而设计的,但是,我想知道为什么这个类定义不能编译:

\n
using std::string;\nclass ExtendedString: public string\n{\npublic:\n    using string::string;\n    ExtendedString left(size_type n) const {\n        return substr(0, n>size()?size():n);\n    }\n};\n
Run Code Online (Sandbox Code Playgroud)\n

我收到此错误:

\n
../../src/capel-tool.cpp:21:17: error: could not convert \xe2\x80\x98std::__cxx11::basic_string<_CharT, _Traits, _Alloc>::substr(std::__cxx11::basic_string<_CharT, _Traits, _Alloc>::size_type, std::__cxx11::basic_string<_CharT, _Traits, _Alloc>::size_type) const [with _CharT = char; _Traits = std::char_traits<char>; _Alloc = std::allocator<char>; std::__cxx11::basic_string<_CharT, _Traits, _Alloc>::size_type = long unsigned int](0, ((n > ((const ExtendedString*)this)->ExtendedString::<anonymous>.std::__cxx11::basic_string<char>::size()) ? ((const ExtendedString*)this)->ExtendedString::<anonymous>.std::__cxx11::basic_string<char>::size() : n))\xe2\x80\x99 from \xe2\x80\x98std::__cxx11::basic_string<char>\xe2\x80\x99 to \xe2\x80\x98ExtendedString\xe2\x80\x99\n
Run Code Online (Sandbox Code Playgroud)\n

我预计left函数将使用 std::string 中的任何默认构造函数。

\n

即使我添加一个像这样的显式构造函数:

\n
using std::string;\nclass ExtendedString: …
Run Code Online (Sandbox Code Playgroud)

c++ inheritance stdstring

1
推荐指数
1
解决办法
102
查看次数

标签 统计

c++ ×1

inheritance ×1

stdstring ×1