C++关键字delete

关键字delete

C++11中,定义成员函数,可在后面使用= delete修饰,表示该函数被删除,禁用;

用法

1.私有构造

我们不希望一个类被拷贝的时候,可以在构造函数前加private,c++11中,只需要在构造后添加= delete修饰即可;

2.禁止隐式转换

class Test
{
public:
	void func(int a)
    {
        printf("%d\n",a);
    }
};

int main()
{
    Test test;
    test.func(13);
    test.func(13.12);
    return 0;
}

输出结果为:

image-20211003174853535

传参时13.12被隐转为整型,可将double类型的重载禁用可禁止隐式转换;

class Test
{
public:
	void func(int a)
    {
        printf("%d\n",a);
    }
    void func(double a) = delete;
};

int main()
{
    Test test;
    test.func(13);
    test.func(13.12);
    return 0;
}
posted @ 2021-10-03 18:21  小紫苏  阅读(932)  评论(0编辑  收藏  举报