• 85、构造函数的几种关键字


    default

    default关键字可以显式要求编译器生成合成构造函数,防止在调用时相关构造函数类型没有定义而报错

    #include <iostream>
    using namespace std;
    class CString
    {
    public:
    CString() = default; //语句1
    //构造函数
    CString(const char* pstr) : _str(pstr){}
    void* operator new() = delete;//这样不允许使用new关键字
    //析构函数
    ~CString(){}
    public:
    string _str;
    };
    int main()
    {
    auto a = new CString(); //语句2
    cout << "Hello World" <<endl;
    return 0;
    }
    //运行结果
    //Hello World

    如果没有加语句1,语句2会报错,表示找不到参数为空的构造函数,将其设置为default可以解决这个问题

    delete

    delete关键字可以删除构造函数、赋值运算符函数等,这样在使用的时候会得到友善的提示

    #include <iostream>
    using namespace std;
    class CString
    {
    public:
    void* operator new() = delete;//这样不允许使用new关键字
    //析构函数
    ~CString(){}
    };
    int main()
    {
    auto a = new CString(); //语句1
    cout << "Hello World" <<endl;
    return 0;
    }

    0:

    将虚函数定义为纯虚函数(纯虚函数无需定义,= 0只能出现在类内部虚函数的声明语句处;当然,也 可以为纯虚函数提供定义,不过函数体必须定义在类的外部)

  • 相关阅读:
    js递归优化
    音视频混流
    JS的发布订阅模式
    redhat7.4 docker run启动容器报错container_linux.go:449
    使用Docker部署vue的前端应用过程
    Mac下安装pip
    powerDesigner 把name项添加到注释
    SQL SERVER 2012 连接报错
    CentOS minimal 安装图形界面
    SQLServer2008卸载后重装问题
  • 原文地址:https://www.cnblogs.com/crbhf/p/15088156.html
Copyright © 2020-2023  润新知