相关疑难解决方法(0)

喜欢构成而不是继承?

为什么喜欢构图而不是继承呢?每种方法都有哪些权衡取舍?什么时候应该选择继承而不是作文?

language-agnostic oop inheritance composition aggregation

1538
推荐指数
23
解决办法
29万
查看次数

有关使用用户定义的方法扩展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万
查看次数