为什么喜欢构图而不是继承呢?每种方法都有哪些权衡取舍?什么时候应该选择继承而不是作文?
我从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)