explicit && delete && default 注意事项

explicit显式的意思. 使用该关键字修饰构造函数可以防止隐式转换复制初始化. 对于转换函数, 可以防止隐式转换.

class num {
    public:
        explicit num(int){}
        explicit operator bool() const {}
}

num n = 1; // 错误
num n = {1}; // 错误
bool b = n; // 错误

delete关键字修饰函数, 可以在编译期就禁用被修饰的函数.

class num {
    public:
        num(int) = delete;
        num(const num&) = delete;
        num& operator = (const num&) = delete;

        void add(int) = delete;

        // 禁止在堆上创建对象
        void *operator new(size_t) = delete;
         void *operator new[](size_t) = delete;
}

default关键字修饰构造函数, 编译器会自动生成函数体.

class num {
    public:
        num() = default;
        num(int) {}
        virtual ~num() = default;
}

如果觉得有帮助,可以扫描右边的微信打赏码支持一下.

Leave a Reply

Your email address will not be published. Required fields are marked *