• C++构造函数实例


    #include<iostream>
    #include <string>
    using namespace std;
    
    class Person
    {
    public:
    //无参(默认)构造函数
        Person()
        {
            cout << "no" << endl;
        }
    //有参构造函数
        Person(int a)
        {
            age = a;
            cout << "is" << endl;
        }
    //拷贝构造函数
        Person(const Person& p)
        {
            age = p.age;
            cout << "copy" << endl;
        }
    //析构函数
        ~Person()
        {
            cout << "de" << endl;
        }
    public:
        int age;
    };
    void test01()
    {
        Person p1(18);
    //如果不写拷贝构造,编译器会自动添加拷贝构造,并且做浅拷贝操作
        Person p2(p1);
        cout << "p2 age = " << p2.age << endl;
    }
    void test02()
    {
    //如果用户提供有参构造,编译器不会提供默认构造,会提供拷贝构造
        Person p1; //此时如果用户自己没有提供默认构造,会出错
        Person p2(10); //用户提供的有参
        Person p3(p2); //此时如果用户没有提供拷贝构造,编译器会提供
    //如果用户提供拷贝构造,编译器不会提供其他构造函数
        Person p4; //此时如果用户自己没有提供默认构造,会出错
        Person p5(10); //此时如果用户自己没有提供有参,会出错
        Person p6(p5); //用户自己提供拷贝构造
    }
    int main()
    {
        test02();
        system("pause");
        return 0;
    }
    

      

  • 相关阅读:
    武功秘籍 蓝桥杯
    切面条 蓝桥杯
    啤酒和饮料 蓝桥杯
    蚂蚁感冒 蓝桥杯
    hdu N!
    hdu 神、上帝以及老天爷
    ListView滑动删除 ,仿腾讯QQ
    C++ 习题 输出日期时间--友元函数
    C++习题 商品销售
    渠道运营一点事
  • 原文地址:https://www.cnblogs.com/CodeWorkerLiMing/p/11098265.html
Copyright © 2020-2023  润新知