c++自定义类型中有个vector容器,容器里面是一些指针,如何写这个类的复制构造函数和重载=符?

 我来答
yyjie999
2013-11-18 · TA获得超过199个赞
知道小有建树答主
回答量:197
采纳率:100%
帮助的人:181万
展开全部
//c++自定义类型中有个vector容器,容器里面是一些指针,如何写这个类的复制构造函数和重载=符?
#include <vector>
#include <iostream>
using namespace std;

class Element
{
public:
Element(int data) {
cout<<__FUNCTION__<<" is called."<<endl;
m_data = data;
}
~Element() {
cout<<__FUNCTION__<<" is called."<<endl;
}
void show() const {
cout<<m_data<<endl;
}
private:
int m_data;
};

class Foo
{
public:
Foo() {
cout<<__FUNCTION__<<" is called."<<endl;
}
~Foo() {
cout<<__FUNCTION__<<" is called."<<endl;
for (int i = 0; i < m_elms.size(); ++i)
delete m_elms.at(i);
m_elms.clear();
}

Foo(const Foo& other) {
cout<<__FUNCTION__<<" is called."<<endl;
for (int i = 0; i < other.m_elms.size(); ++i) {
Element *p1 = other.m_elms.at(i);
Element *p2 = new Element(*p1);
m_elms.push_back(p2);
}
}
Foo &operator=(const Foo &other) {
cout<<__FUNCTION__<<" is called."<<endl;
if (&other != this) {
for (int i = 0; i < m_elms.size(); ++i) {
delete m_elms.at(i);
}
m_elms.clear();
for (int i = 0; i < other.m_elms.size(); ++i) {
Element *p1 = other.m_elms.at(i);
Element *p2 = new Element(*p1);
m_elms.push_back(p2);
}
}

return *this;
}

void addElem(Element *elem)
{
m_elms.push_back(elem);
}

void show() {
cout<<"Foo::show:"<<endl;
for (int i = 0; i < m_elms.size(); ++i)
m_elms.at(i)->show();
cout<<endl;
}
private:
vector<Element *> m_elms;
};

int main()
{
Foo *foo1 = new Foo();;
foo1->addElem(new Element(1));
foo1->addElem(new Element(2));
foo1->addElem(new Element(3));
foo1->show();
delete foo1;
cout<<"----------------"<<endl;

foo1 = new Foo();
foo1->addElem(new Element(11));
// copy constructor called
Foo *foo2 = new Foo(*foo1);
foo2->addElem(new Element(8));
foo1->show();
foo2->show();
cout<<"-----------------"<<endl;
delete foo1;
foo2->show();
cout<<"-----------------"<<endl;

Foo *foo3 = new Foo();;
// = called
*foo3 = *foo2;
foo3->show();

*foo3 = *foo2;
foo3->show();

return 0;
}
追问
NENG不能用copy和迭代器
追答
如果你有更好的方法,就不用在这里问了
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式