我从C++ STL容器继承并添加我自己的方法.理由是,对于客户来说,它看起来像是一个常规列表,但是它们可以很容易地被称为特定于应用程序的方法.
这很好,但我读过很多关于不从STL继承的帖子.有人可以提供一个具体的建议,告诉我如何以更好的方式编写下面的代码吗?
class Item
{
int a;
int b;
int c;
int SpecialB()
{
return a * b + c;
}
};
class ItemList : public std::vector<Item>
{
int MaxA()
{
if( this->empty() )
throw;
int maxA = (*this)[0].a;
for( int idx = 1; idx < this->size(); idx++ )
{
if( (*this)[idx].a > maxA )
{
maxA = (*this)[idx].a;
}
}
return maxA;
}
int SpecialB()
{
if( this->empty() )
throw;
int specialB = (*this)[0].SpecialB();
for( int idx = …Run Code Online (Sandbox Code Playgroud) 既然std::string实际上是typedef模板类,我怎么能覆盖呢?我想制作一个std::string能返回正确长度的UTF-8 .
我知道 std::string不是为继承而设计的,但是,我想知道为什么这个类定义不能编译:
\nusing 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};\nRun 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\nRun Code Online (Sandbox Code Playgroud)\n我预计left函数将使用 std::string 中的任何默认构造函数。
即使我添加一个像这样的显式构造函数:
\nusing std::string;\nclass ExtendedString: …Run Code Online (Sandbox Code Playgroud)