簡體   English   中英

=刪除用戶定義的成員函數,除了構造函數,賦值運算符c ++ 11

[英]=delete for user defined member functions apart from constructor, assignment operator 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()函數,因此沒有其他函數可以調用它。

想知道是否存在使用/推薦這種類型的函數聲明(繪畫)的場景。

因此,沒有任何東西可以從過載中受益。

#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
}
  • 提供更嚴格的輸入參數檢查:

 void foo(void *){}

 void foo(int) = delete;

 foo(0); // error
  • 將方法標記為“未明確實現”,當一類類具有某些功能但由於性能或其他原因而無法提供該功能時,這可能會很有用:

class my_list
{
    // you should use other container if you need constant time size
    public: size_t size(void) = delete;     
};
  • 作為功​​能棄用的最后一步。 有些甚至使用專用宏。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM