- 默认情况下,c++编译器至少给一个类添加3个函数
- 默认构造函数(无参,函数体为空)
- 默认析构函数(无参,函数体为空)
- 默认拷贝构造函数,对属性进行值拷贝
- 构造函数调用规则如下
using namespace std;
// 构造函数调用规则 // 1.创建一个类,C++编译器会给每个类添加3个函数 // 默认构造(空实现) // 析构函数(空实现) // 拷贝构造(值拷贝)
// 2.如果我们写了有参构造,编译器就不再提供默认构造,依然提供拷贝构造 // 如果我们写了拷贝构造函数,编译器就不再提供其他的构造函数了 class Person {
public: //Person() { // cout << “Person 的默认构造函数” << endl; //}
//Person(int val) {// age = val;// cout << "Person 的有参构造函数" << endl;//}Person(const Person &p) {age = p.age;cout << "Person 的拷贝构造函数" << endl;}~Person() {cout << "Person 的析构函数" << endl;}int age;
};
void test01() { //Person p; //p.age = 18; //Person p2(p); //cout << “p2的年龄:” << p2.age << endl; }
void test02() { //Person p(28);
//Person p2(p);//cout << "p2的年龄:" << p2.age << endl;
}
void test03() {
} int main() { //test01(); //test02(); test03(); system(“pause”); return 0; } ```
