class DataOnly { public: DataOnly () // default constructor ~DataOnly () // destructor DataOnly (const DataOnly & rhs) // copy constructor DataOnly & operator=(const DataOnly & rhs) // copy assignment operator DataOnly (const DataOnly && rhs) // C++11, move constructor DataOnly & operator=(DataOnly && rhs) // C++11, move assignment operator };
假如上面的几个函数中,不想使用其中某个,能够将其定义为private
,或者使用=delete
。ios
#include <iostream> using namespace std; class DataOnly { public: DataOnly () {} ~DataOnly () {} DataOnly (const DataOnly & rhs) = delete; //禁止使用该函数 DataOnly & operator=(const DataOnly & rhs) = delete; //禁止使用该函数 DataOnly (const DataOnly && rhs) {} DataOnly & operator=(DataOnly && rhs) {} }; int main(int argc, char *argv[]) { DataOnly data1; DataOnly data2(data1); // error: call to deleted constructor of 'DataOnly' DataOnly data3 = data1; // error: call to deleted constructor of 'DataOnly' return 0; }
#include <iostream> using namespace std; class DataOnly { public: void fun(int a) {} void fun(float a) = delete; }; int main(int argc, char *argv[]) { DataOnly data1; data1.fun(1); // OK data1.fun(0.5); // error: call to member function 'fun' is ambiguous return 0; }
例如:Widget 类中声明了一个模板函数,当进行模板特化时,要求禁止参数为 void* 的函数调用。
1. 按照私有不实现
思路,应该是将特例化的函数声明为私有型,以下:程序员
#include <iostream> using namespace std; class Widget { public: template<typename T> void ProcessPointer(T* ptr) { cout << typeid (T).name() << endl; } private: void ProcessPointer(void*) { cout << "void" << endl; } }; int main(int argc, char *argv[]) { Widget w; int* ip = NULL; w.ProcessPointer(ip); void* vp = NULL; w.ProcessPointer(vp); //error: 'ProcessPointer' is a private member of 'Widget' w.ProcessPointer(vp); return 0; }
在程序员重载了本身上面提到的C++编译器默认生成的函数以后,C++编译器将不在生成这些函数的默认形式。
可是C++容许咱们使用=default来要求编译器生成一个默认函数,如函数
struct Point { Point()=default; Point(int _x, int _y) : x(_x), y(_y) {} int x = 0; int y = 0; }
这样至关于无参的构造函数也是能够使用的spa
本文转自:https://blog.csdn.net/lmb1612977696/article/details/80035487.net