使用' operator '关键字是什么意思?

What does this use of the `operator` keyword mean?

本文关键字:意思 是什么 operator 使用 关键字      更新时间:2023-10-16

我在cppreference.com上发现了以下代码(我正在查找explicit关键字的含义)

struct A
{
    A(int) {} // converting constructor
    A(int, int) {} // converting constructor (C++11)
    operator int() const { return 0; }
};

在结构体定义的第三行有这样一行:operator int() const { return 0; }

我不确定这行是做什么的。哪个操作符被重载了,是int吗?

我看了这里,想自己弄清楚这个问题,但我还是摸不着头脑。

是用户定义的转换操作符

http://en.cppreference.com/w/cpp/language/cast_operator

struct X {
    //implicit conversion
    operator int() const { return 7; }
    // explicit conversion
    explicit operator int*() const { return nullptr; }
//   Error: array operator not allowed in conversion-type-id
//   operator int(*)[3]() const { return nullptr; }
    using arr_t = int[3];
    operator arr_t*() const { return nullptr; } // OK if done through typedef
//  operator arr_t () const; // Error: conversion to array not allowed in any case
};
int main()
{
    X x;
    int n = static_cast<int>(x);   // OK: sets n to 7
    int m = x;                     // OK: sets m to 7
    int* p = static_cast<int*>(x);  // OK: sets p to null
//  int* q = x; // Error: no implicit conversion
    int (*pa)[3] = x;  // OK
}