c++自定义类型中有个vector容器,容器里面是一些指针,如何写这个类的复制...
发布网友
发布时间:2024-04-07 17:25
我来回答
共1个回答
热心网友
时间:2024-07-22 12:11
//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;
}