首页 > 解决方案 > =删除用户定义的成员函数,除了构造函数,赋值运算符c ++ 11

问题描述

在 C++11 中,我们使用“= delete”来禁止在执行某些操作(更改数据类型/对象分配)时隐式调用构造函数和运算符重载的成员函数。

class color{
 public:    
 color(){cout<<"color constructed called"<<endl;}
 color(int a){};
 color(float)=delete;
 color& operator = (color &a) = delete;
 virtual void paint() = delete;  //What is the use of delete in this function
 //void paint() = delete; The above virtual is not mandatory, just a generic scenario.
 virtual void paints () final {};
};

在上面的示例中,我在用户定义的成员函数上使用了 delete。它说我们可以定义paint() 函数,因此没有其他函数可以调用它。

想知道是否存在这种类型的函数声明(绘制)有用/推荐的场景。

标签: c++c++11delete-operator

解决方案


因此,这种过载没有任何好处。

#include <iostream>

struct Nyan {
    int omg(int x) { return x + 2; }
};

struct Meow {
    int omg(int x) { return x + 2; }
    int omg(double) = delete;
};

int main() {
    Nyan n;
    Meow m;
    std::cout << n.omg(40) << std::endl;
    std::cout << m.omg(40) << std::endl;
    std::cout << n.omg(40.5) << std::endl;
    // std::cout << m.omg(40.5) << std::endl; // commented out for a reason
}

推荐阅读