前言:构造函数有3种,见代码。构造函数的调用也有3种,但个人认为只有括号法较为简便,所以只需掌握括号法调用就可以。如果写了有参构造,编译器就不再提供默认构造;如果写了拷贝构造,编译器就不再提供其他构造。
#include<iostream>
using namespace std;
class person
{
public:
//构造函数-----相当于开始时初始化
//①无参构造函数(默认构造函数)
person()
{
cout << "aaaaaaaa" << endl;
}
//②有参构造函数
person(int a, int h)
{
age = a;
height = new int(h); //堆区存放身高h
cout << "bbbbbbbbb" << endl;
}
//③拷贝构造函数
person(const person& p)
{
cout << "cccccccc" << endl;
age = p.age;
height = new int(*p.height); //深拷贝:重新开辟一个内存存放身高的地址,避免编译器浅拷贝带来的内存释放冲突问题
}
//析构函数-----相当于结束时清空
~person()
{
if (height != NULL) //堆区开辟的内存使用完进行释放
{
delete height;
height = NULL;
}
cout << "dddddddddd" << endl;
}
//成员变量
int age;
int* height;
};
void test1()
{
person p1; //无参构造函数调用
person p2(20,160);//有参构造函数调用
cout << p2.age << "\t" << *p2.height << endl;
person p3(p2);//拷贝构造函数调用
cout << p2.age << "\t" << *p2.height << endl;
cout << endl;
}
int main()
{
test1();
system("pause");
return 0;
}
运行结果: