• 默认情况下,c++编译器至少给一个类添加3个函数
    • 默认构造函数(无参,函数体为空)
    • 默认析构函数(无参,函数体为空)
    • 默认拷贝构造函数,对属性进行值拷贝
  • 构造函数调用规则如下
    • 如果用户定义有参构造函数,c++不在提供默认无参构造,但是会提供默认拷贝构造
    • 如果用户定义拷贝构造函数,C++不在提供其他构造函数 ```cpp

      include

      include

using namespace std;

// 构造函数调用规则 // 1.创建一个类,C++编译器会给每个类添加3个函数 // 默认构造(空实现) // 析构函数(空实现) // 拷贝构造(值拷贝)

// 2.如果我们写了有参构造,编译器就不再提供默认构造,依然提供拷贝构造 // 如果我们写了拷贝构造函数,编译器就不再提供其他的构造函数了 class Person {

public: //Person() { // cout << “Person 的默认构造函数” << endl; //}

  1. //Person(int val) {
  2. // age = val;
  3. // cout << "Person 的有参构造函数" << endl;
  4. //}
  5. Person(const Person &p) {
  6. age = p.age;
  7. cout << "Person 的拷贝构造函数" << endl;
  8. }
  9. ~Person() {
  10. cout << "Person 的析构函数" << endl;
  11. }
  12. int age;

};

void test01() { //Person p; //p.age = 18; //Person p2(p); //cout << “p2的年龄:” << p2.age << endl; }

void test02() { //Person p(28);

  1. //Person p2(p);
  2. //cout << "p2的年龄:" << p2.age << endl;

}

void test03() {

} int main() { //test01(); //test02(); test03(); system(“pause”); return 0; } ```