簡體   English   中英

C++ 轉換運算符重載

[英]C++ conversion operator overload

“int”和“double”轉換函數是“explicit”,在這段代碼中,為什么我允許使用這種轉換而不是錯誤消息? 如果我刪除所有轉換重載函數代碼會發生“轉換錯誤”

class Person
{
public:
    Person(string s = "", int age = 0) :Name(s), Age(age) {}
    operator string() const { return Name; }
    explicit operator int() const{ return 10; }  // ! Explicit
    explicit operator double()const { return 20; } //! Explicit
    operator bool()const { if (Name != "") return true; return false; } // using this
};

int main(){

    Person a;
    int z = a;
    std::cout << z << std::endl;   // Why print "1"?  Why uses bool conversion?
}

我這是答案:

因為 'a' 不能轉換為 int 或 double 會發生錯誤,但因為它有 bool 轉換功能,可以轉換為 int 和 int 為 double,代碼使用此功能。

int z = a;

看起來無害,對吧?

好吧,上面的行調用了隱式 bool-conversion-operator,因為這是您離開它從Personint的唯一方法,並且只需要一個用戶定義的轉換(允許的最大值)。

這就是在 C++11 之前使用 safe-bool-idiom 的原因,也是一般建議將轉換運算符和單參數 ctor 標記為explicit的主要原因,除非它們不是可轉換的或有損的。

如果您想親自查看它,請修復您的代碼並跟蹤對operator bool的調用

暫無
暫無

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

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