相关疑难解决方法(0)

有关使用用户定义的方法扩展C++ STL容器的更好方法的建议

我从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)

c++ stl

12
推荐指数
4
解决办法
1万
查看次数

继承和覆盖std :: string的函数?

既然std::string实际上是typedef模板类,我怎么能覆盖呢?我想制作一个std::string能返回正确长度的UTF-8 .

c++ unicode utf-8 character-encoding

12
推荐指数
2
解决办法
5398
查看次数

无法围绕 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++ ×3

character-encoding ×1

inheritance ×1

stdstring ×1

stl ×1

unicode ×1

utf-8 ×1