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;
}
输出结果为:
传参时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;
}
Life is too short for so much sorrow.
本博客所有文章除特别声明外,均采用
CC BY-NC-SA 4.0 许可协议。转载请注明来自 小紫苏!