operator MyClass*() 的意思是什么?

4

我有以下类定义:

struct MyClass { 
   int id;
   operator MyClass* () { return this; }
};

我对上面代码中的operator MyClass* ()这一行很困惑。你有什么想法吗?


2
这是一个转换运算符 - Bo Persson
谢谢,我会查看链接URL。 - kinjia
@kinjia "上面代码中的 MyClass* () 运算符是干什么用的" - 除了代码作者,没有人知道这个问题的答案。 :) - Vlad from Moscow
2个回答

7

这是一种类型转换运算符。它允许将类型为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
}

至于为什么定义了转换,这是有争议的。坦白说,我从未见过这种情况,并且无法猜测为什么要定义它。


1
谁写的这段代码可能试图模拟引用 :P - Rakete1111
1
@Rakete1111 - 我知道,是吧?如果C++也有它们就好了 :P - StoryTeller - Unslander Monica

1
这是一种用户自定义转换,允许从一个类类型隐式或显式地转换为另一种类型。

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)
  1. Declares a user-defined conversion function that participates in all implicit and explicit conversions

  2. Declares a user-defined conversion function that participates in direct-initialization and explicit conversions only.


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接