gpt4 book ai didi

c++ - =delete 用于用户定义的成员函数,除了构造函数、赋值运算符 c++11

转载 作者:太空宇宙 更新时间:2023-11-03 10:38:52 30 4
gpt4 key购买 nike

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

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

想知道是否有任何场景可以使用/推荐这种类型的函数声明(paint)。

最佳答案

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

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

关于c++ - =delete 用于用户定义的成员函数,除了构造函数、赋值运算符 c++11,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50080976/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com