简体   繁体   中英

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

In the Halide's source code, I read this line of code:

operator halide_type_t() const { return type; }

in the definition of the a class named Type , and it contains a member type which is halide_type_t struct.

I am a little confused about the operator overloading, and how should I use the new function halide_type_t() ?

Consider the code below:

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
}

In this case, user-defined conversion takes place. Whenever an object of number is assigned to a float value, the conversion takes place and the value is returned. In your case, when an object of class Type is assigned to struct halide_type_t, ie

  Type t1;
  halide_type_t t = t1;

the value of t1.type is assigned to t. Hope it helps! :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM