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