我有以下类定义:
struct MyClass {
int id;
operator MyClass* () { return this; }
};
我对上面代码中的operator MyClass* ()
这一行很困惑。你有什么想法吗?
我有以下类定义:
struct MyClass {
int id;
operator MyClass* () { return this; }
};
我对上面代码中的operator MyClass* ()
这一行很困惑。你有什么想法吗?
这是一种类型转换运算符。它允许将类型为MyClass
的对象隐式转换为指针,而无需使用取地址运算符。
以下是一个小例子以说明:
void foo(MyClass *pm) {
// Use pm
}
int main() {
MyClass m;
foo(m); // Calls foo with m converted to its address by the operator
foo(&m); // Explicitly obtains the address of m
}
至于为什么定义了转换,这是有争议的。坦白说,我从未见过这种情况,并且无法猜测为什么要定义它。
cppreference 参考资料:
Syntax :
Conversion function is declared like a non-static member function or member function template with no parameters, no explicit return type, and with the name of the form:
operator conversion-type-id (1) explicit operator conversion-type-id (2) (since C++11)
Declares a user-defined conversion function that participates in all implicit and explicit conversions
Declares a user-defined conversion function that participates in direct-initialization and explicit conversions only.