C ++-复制构造函数或带有继承的指针列表的重载Operator =

问题描述 投票:0回答:1

我有一个从指针列表继承的Class,例如:

Class C : protected list<Type*>

现在,我想重载operator =(并编写副本构造函数)。我应该迭代列表为列表中的每个指针创建一个新的Type吗?

void C::operator=(const C& c)
{
    if(!(*this)==c))
    {
        clear();
        for(list<Type*>::iterator it = c.begin(); it != c.end(); it++)
        {
           Type* cp = new Type((*it)); //or doing cp=&(*it) after the new
           push_back(cp);
        }
    }
}

或者我可以这样做吗?

void C::operator=(const C& c)
{
    if(!(*this)==c))
    {
        clear();
        for(list<Type*>::iterator it = c.begin(); it != c.end(); it++)
        {
           Type* cp = it; //or cp=&(*it)
           push_back(cp);
        }
    }
}
c++ overloading copy-constructor assignment-operator
1个回答
0
投票
std::list已具有您未使用的operator=。相反,您正在重新发明它。 (这实际上强调了我先前的发言。)

所以:

#include <list> template<typename T> class C { private: std::list<T*> lst; public: C& operator=(const C& c) { if (this != &c) { lst = c.lst; } return *this; } };

和瞧。

© www.soinside.com 2019 - 2024. All rights reserved.