using namespace std;
// 构造函数的分类及调用
// 分类
// 无参构造(默认构造),有参构造
// 类型
// 普通构造函数,拷贝构造函数
class Person {
public:
Person() {
cout << “Person 的构造函数调用” << endl;
};
Person(int a) {
age = a;
cout << “Person 的有参构造函数调用” << endl;
}
// 拷贝构造函数Person(const Person &p) {// 将传入的人身上的所有属性,拷贝到我身上age = p.age;cout << "Person 的拷贝构造函数调用" << endl;}int age;~Person() {cout << "Person 的析构函数调用" << endl;}
};
void test01() { //// 1.括号法 //Person p; // 默认构造函数调用 //Person p2(10); // 有参构造函数 //// 拷贝构造函数 //Person p3(p2);
//// 注意事项//// 调用默认构造函数时,不要+()//// 因为这行代码,编译器认为是一个函数的申明,不会认为在创建对象//// Person p1();//cout << "p2的年龄为: " << p2.age << endl;//cout << "p3的年龄为: " << p3.age << endl;// 2.显示法Person p;Person p2 = Person(10); // 有参构造// 拷贝构造Person p3 = Person(p3);// 匿名对象, 特点:当前行结束后,系统会立即回收掉匿名对象//Person(10);//cout << "aaaa" << endl;// 注意事项2// 不要利用拷贝函数,初始化匿名对象, 编译器会认为 Person(p3) === Person p3; 认为是对象声明//Person(p3);// 3.隐式转换法Person p4 = 10; // 相当于 写了 Person p4 = Person(10); 有参构造Person p5 = p4; // 拷贝构造
} int main() { test01();
system("pause");return 0;
} ```
