为什么在 C++ 中调用这个运算符?
我不明白,为什么在最后第二行调用 aaa 运算符?
#include <iostream>
class MyClass
{
private:
typedef void (MyClass::*aaa)() const;
void ThisTypeDoesNotSupportComparisons() const {}
public:
operator aaa() const { return (true) ? &MyClass::ThisTypeDoesNotSupportComparisons : 0; }
};
int main()
{
MyClass a;
MyClass b;
if(a && b) {}
}
I dont understand, why is the aaa operator called in the 2nd last line?
#include <iostream>
class MyClass
{
private:
typedef void (MyClass::*aaa)() const;
void ThisTypeDoesNotSupportComparisons() const {}
public:
operator aaa() const { return (true) ? &MyClass::ThisTypeDoesNotSupportComparisons : 0; }
};
int main()
{
MyClass a;
MyClass b;
if(a && b) {}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
编译器搜索 (a && b) 的最佳匹配。
由于该类没有将 MyClass 转换为布尔值的运算符,因此它会搜索最佳演员表。
operator aaa() const 是对 aaa 类型指针的强制转换。可以在 if 语句中评估指针。
重载类型转换
转换函数 (C++)
The compiler searches for the best match for (a && b).
Because the class doesn't have an operator that turns MyClass to a boolean, it searches for the best cast.
operator aaa() const is a cast to an aaa type pointer. Pointers can be evaluated in an if sentence.
Overloading typecasts
Conversion Functions (C++)
您的变量在表达式中使用。类型本身没有运算符&&为其定义,但它可以转换为可以在表达式中使用的类型(指针)。因此调用转换运算符。
Your variables are used in an expression. The type itself does not have an operator&& defined for it, but it is convertible to a type (a pointer) that can be used in the expression. So the conversion operator is called.
它看起来像一个类型转换运算符。哎呀,没关系,将“为什么调用这个运算符”误读为“这个运算符叫什么”
好吧,我测试了你的代码并进一步检查了它。所以运算符 aaa 是类型转换为 aaa 类型。 aaa 类型是指向 void func() 类型的成员函数的指针。 ThisTypeDoesNotSupportComparisons 是 aaa 类型的函数。运算符 aaa 被调用并返回函数指针。
我认为它被调用是因为 if 也允许使用函数指针。您可以测试指针是否为 NULL,这是编译器可以找到的最接近的值,因此 if 调用运算符 aaa 并测试返回的指针是否为零。
It looks like a type cast operator. Oops, never mind, misread 'why is this operator called' for 'what is this operator called'
Ok, I tested your code and examined it some more. So operator aaa is a type cast to type aaa. Type aaa is a pointer to a member function of type void func(). ThisTypeDoesNotSupportComparisons is a function of type aaa. operator aaa gets called and returns the pointer to function.
I think it is called because the if allows to use pointers to functions as well. You can test if a pointer is NULL or not, and this is the closest the compiler can find, so if calls the operator aaa and tests if the pointer returned is zero.