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;
}

输出结果为:

C++关键字delete

传参时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;
}

相关文章:

  • 2021-06-05
  • 2022-02-04
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-09-07
  • 2021-11-16
  • 2022-01-07
相关资源
相似解决方案