#include<iostream>
#include<stdlib.h>
using namespace std;
class A
{
public:
A(int i, int j){ n = i; m = j; }
A(A &t){ n = t.n; m = t.m; }//默认的复制构造函数,即使把这一行注释掉仍能正确执行
void print(){ cout << n << m << endl; }
private:
int n;
int m;
};
int main()
{
A a(2, 4);
a.print();
A b(a);
b.print();
system("pause");
return 0;
}
#include<iostream>
#include<stdlib.h>
using namespace std;
class A
{
public:
A(){ x = new int; *x = 5; }
~A(){ delete x; x = NULL; }
//A(const A&a){ cout << "复制构造函数执行" << endl; x = a.x; }//即使我们不写这样一个复制构造函数,系统也会默认存在这样一个复制构造函数。浅拷贝
A(const A&a){ cout << "复制构造函数执行" << endl; x = new int; *x = *(a.x); }//深拷贝
void print()const{ cout << *x; }
void set(int i){ *x = i; }
private:
int *x;
};
int main()
{
A *a = new A;
cout << "a:"; a->print();cout << endl;
A b = *a;
a->set(32);
cout << "b:"; b.print(); cout << endl;
b.set(99);
cout << "a:"; a->print(); cout << endl;
system("pause");
return 0;
}
默认构造函数的复制方式,叫做成员拷贝,又叫浅拷贝,这种浅拷贝方式易出现迷途指针。