偷偷拿来记录一下萌新的cs路——day 23 对象特性-构造函数、析构函数、拷贝函数调用时机、规则。
#include<iostream>
using namespace std;
class person {
public:
// 构造函数:不用void,无返回值,函数名与类名相同,可有参数可发生重载,创建对象时会且仅会调用一次
person() {
cout << "person无参(默认)构造函数调用" << endl;
}
person(int a) {
age = a;
cout << "person有参构造函数调用" << endl;
}
// 拷贝构造函数
person(const person& p) {
age = p.age;
cout << "person拷贝构造函数调用" << endl;
}
// 析构函数:不用void,无返回值,函数名与类名相同,前加~,不可有参数不可重载,对象在销毁前自动调用析构函数
~person() {
cout << "person析构函数调用" << endl;
}
int age;
};
// 调用
void test01() {
// 括号法
person p1; // 默认构造函数调用(不能加(),否则编译器认为是函数声明而非创建对象)
person p2(10); // 栈区数据,test01执行完毕释放对象
person p3(p2); // 拷贝构造函数调用
cout << "p2年龄:" << p2.age << endl;
cout << "p3年龄:" << p3.age << endl;
cout << endl;
//显示法
person p4 = person(20); // 有参构造
person p5 = person(p2); // 拷贝构造
person(20); // 匿名对象:当前操作结束后系统立即回收;不要利用拷贝构造函数初始化匿名对象
cout << endl;
//隐式转换法
person p6 = 30; // 有参构造:相当于person p6 = person(30)
person p7 = p6; // 拷贝构造
cout << endl;
}
// 值传递方式给函数参数传值
void doWork(person p) {
}
void test02(){
person p;
doWork(p);
}
// 值方式返回局部对象
person doWork2() {
person p8;
cout << "address of p8: " << (int*)&p8 << endl;
return p8;
}
void test03() {
person p = doWork2();
cout << "address of p_test03: " << (int*)&p << endl;
}
int main() {
test01();
cout << endl;
test02();
cout << endl;
test03();
//person p;
system("pause");
return 0;
}
运行结果
用户定义有参构造函数:编译器不提供无参构造,提供默认拷贝构造
用户定义拷贝构造函数:编译器不提供其他构造
以后学了更多知识还会回来更新的!有误之处恳请大佬指正,提前感谢!