c – 为什么成员函数temporaries不绑定到正确的类型?

c – 为什么成员函数temporaries不绑定到正确的类型?,第1张

概述假设我们有以下基类和派生类: #include <string>#include <iostream>class Car {public: void Drive() { std::cout << "Baby, can I drive your car?" << std::endl; }};class Porsche : public Car {}; ..还有以下模板功能: 假设我们有以下基类和派生类:
#include <string>#include <iostream>class Car {public:    voID Drive() { std::cout << "Baby,can I drive your car?" << std::endl; }};class Porsche : public Car {};

..还有以下模板功能:

template <typename T,typename V>voID Function(voID (T::*m1)(voID),voID (V::*m2)(voID)) {    std::cout << (m1 == m2) << std::endl;}

为什么使用GCC编译:

int main(int argc,char** argv) {    voID (Porsche::*ptr)(voID) = &Porsche::Drive;    Function(ptr,ptr);    return 0;}

……但不是吗?

int main(int argc,char** argv) {    voID (Porsche::*ptr)(voID) = &Porsche::Drive;    Function(&Porsche::Drive,ptr);    return 0;}
解决方法
int main(int argc,ptr);    return 0;}

ptr的类型为voID(Porsche :: *)(),但& Porsche :: Drive的类型为voID(Car :: *)()(因为该成员在Car中找到,而不是在Porsche中).因此,调用的函数将这两个成员指针与这些类型进行比较,标准说

In addition,pointers to members can be compared,or a pointer to member and a null pointer constant. Pointer to member conversions (4.11) and qualification conversions (4.4) are performed to bring them to a common type. If one operand is a null pointer constant,the common type is the type of the other operand. Otherwise,the common type is a pointer to member type similar (4.4) to the type of one of the operands,with a cv-qualification signature (4.4) that is the union of the cv-qualification signatures of the operand types.

4.11描述了从voID(Base :: *)()到voID(Derived :: *)()的隐式标准转换.因此,比较会找到常见类型voID(Porsche :: *)().对于Porsche类型的对象,两个成员指针都将引用相同的函数(即Car :: Drive) – 因此比较将产生true. comeau web compiler遵循此解释并编译您的代码.

总结

以上是内存溢出为你收集整理的c – 为什么成员函数temporaries不绑定到正确的类型?全部内容,希望文章能够帮你解决c – 为什么成员函数temporaries不绑定到正确的类型?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/1243589.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-06-06
下一篇2022-06-06

发表评论

登录后才能评论

评论列表(0条)

    保存