在运算符的情况下使用C ++ const转换 [英] C++ const conversion in the case of operators

查看:52
本文介绍了在运算符的情况下使用C ++ const转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下代码:

  struct A {
void operator ++ const {}
};

void operator ++(const A&){}


int main(){
const A ca;
++ ca; // g ++ Error(as expected):'operator ++'的模糊重载

A a;
++ a; // g ++警告:ISO C ++说这些是不明确的,
//即使第一个的最糟糕的转换比第二个
//的最坏的转换更好的
//候选1:void operator ++(const A&)
//候选2:void A :: operator ++()const
}


为什么g ++只在 ++ a 上发出警告而不是错误?换句话说,非成员函数如何比成员函数更合适?



谢谢!

解决方案

如果我猜测,成员函数会从 A * 当初始化 this 时, A const * ,而非成员绑定 A const& 引用一个非const对象,这不是一个真正的转换,但只是一个非首选的情况下在重载解决过程中。



当从参数类型到各个参数类型的路径涉及不同类型的转换时,会出现该消息。标准拒绝比较苹果和橘子,例如。指针资格与引用绑定或整数提升与转换运算符,但GCC愿意。


Consider the following code:

struct A {
    void operator++() const {}
};

void operator++(const A&) {}


int main () {
    const A ca;
    ++ca; // g++ Error (as expected): ambiguous overload for ‘operator++’

    A a;
    ++a; // g++ Warning: "ISO C++ says that these are ambiguous,
         // even though the worst conversion for the first is better
         // than the worst conversion for the second"
         // candidate 1: void operator++(const A&)
         // candidate 2: void A::operator++() const
}

Why is g++ only issuing a warning and not an error on ++a? In other words, how is the non-member function a better fit than the member function?

Thank you!

解决方案

If I were to guess, the member function causes a pointer qualification conversion from A * to A const * when initializing this, whereas the non-member binds an A const & reference to a non-const object, which isn't really a conversion at all but is merely a non-preferred case during overload resolution.

That message comes about when the paths leading from the argument type to the respective parameter types involve different kinds of conversions. The standard refuses to compare apples to oranges, e.g. pointer qualification vs. reference binding or integral promotion vs. conversion operator, but GCC is willing.

这篇关于在运算符的情况下使用C ++ const转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆