理解复制控制成员和构造函数的一个良好方式是定义一个简单的类,该类具有这些成员,每个成员打印自己的名字
#include <iostream>
#include <vector>
using namespace std;
struct Expl {
Expl(){cout << "Expl()" << endl;}
Expl(const Expl &) {cout << "Expl(const Expl&)" << endl;}
Expl& operator=(const Expl&)
{
cout << "Expl& operator=(const Expl&)" << endl;
return *this;
}
~Expl(){cout << "~Expl()" << endl;}
};
void fun1(Expl expl)
{
}
void fun2(Expl &)
{
}
Expl fun3()
{
Expl obj;
return obj;
}
int main (int argc, const char * argv[])
{
// insert code here...
Expl expl;
fun1(expl);
fun2(expl);
expl = fun3();
Expl *p = new Expl;
vector<Expl> evect(3);
delete p;
return 0;
}
编写一个像Expl这样的类,给出复制控制成员和其他构造函数。然后写一个程序,用不同方式使用Expl类型的对象:作为非引用形参和引用形参传递,动态分配,放在容器中,等等。研究何时执行哪个构造函数和复制控制成员,可以帮助你融会贯通地理解这些概念。
下面的输出结果,仅供参考,因为不同版本C++编译结果可能不同
Expl()
Expl(const Expl&)
~Expl()
Expl()
Expl& operator=(const Expl&)
~Expl()
Expl()
Expl()
Expl(const Expl&)
Expl(const Expl&)
Expl(const Expl&)
~Expl()
~Expl()
~Expl()
~Expl()
~Expl()
~Expl()