簡體   English   中英

C++:使用關鍵字運算符重載成員的構造函數

[英]C++: Overload a member's constructor function with keyword operator

在 Halide 的源代碼中,我閱讀了這行代碼:

operator halide_type_t() const { return type; }

在一個名為Type的類的定義中,它包含一個成員type ,它是halide_type_t結構。

我對operator重載有點困惑,我應該如何使用新函數halide_type_t()

考慮下面的代碼:

struct number{
    int numerator;
    int denominator;
    operator float() { return numerator*1.0 / denominator }

}
void main(){
    number n;
    n.numerator = 3;
    n.denominator = 4;
    float value = n; // here the user-defined conversion occurs
    std::cout << value; // 0.75
}

在這種情況下,會發生用戶定義的轉換。 每當將 number 對象分配給浮點值時,就會發生轉換並返回該值。 在您的情況下,當類 Type 的對象分配給 struct halide_type_t 時,即

  Type t1;
  halide_type_t t = t1;

t1.type 的值被賦值給 t。 希望能幫助到你! :)

暫無
暫無

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

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