书本447页:13.13
#include <iostream>
#include <vector>
using namespace std;
struct X
{
X(){ cout << "构造函数X()" << endl; }
X(const X&){ cout << "拷贝构造函数X(const X&)" << endl; }
X& operator=(const X&){ cout << "拷贝赋值运算符=(const X&)" << endl; return *this; }
~X(){ cout << "析构函数~X()" << endl; }
};
void f1(X x)
{
}
void f2(X &x)
{
}
int main()
{
X x;
cout << endl;
cout << "非引用参数传递:" << endl;
f1(x);
cout << endl;
cout << "引用参数传递:" << endl;
f2(x);
cout << endl;
cout << "动态分配:" << endl;
X *px = new X;
cout << endl;
cout << "添加到容器中:" << endl;
vector<X> vx;
vx.push_back(x);
cout << endl;
cout << "释放动态分配对象:" << endl;
X y = x;
y = x;
cout << endl;
cout << "程序结束" << endl;
return 0;
}
结果:
构造函数X()
非引用参数传递:
拷贝构造函数X(const X&)
析构函数~X()
引用参数传递:
动态分配:
构造函数X()
添加到容器中:
拷贝构造函数X(const X&)
释放动态分配对象:
拷贝构造函数X(const X&)
拷贝赋值运算符=(const X&)
程序结束
析构函数~X()
析构函数~X()
析构函数~X()
请按任意键继续. . .