我有一个从指针列表继承的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);
}
}
}
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;
}
};
和瞧。