操作符情况下的c++ const转换



考虑以下代码:

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
}

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

谢谢!

如果我猜,在初始化this时,成员函数导致从A *A const *的指针限定转换,而非成员将A const &引用绑定到非const对象,这根本不是真正的转换,而只是重载解析期间的非首选情况。

当从实参类型到相应形参类型的路径涉及不同类型的转换时,就会出现该消息。标准拒绝将苹果与橙子进行比较,例如指针限定与引用绑定或整型提升与转换操作符,但GCC愿意。

在c++中,可以将const非const的方法(和操作符)分开,当你不这样做时,编译器可以搜索"最适合"的。最适合not const的是const

看一下这个例子:

struct S{
  void f(){cout<<"f";}
  void f()const{cout<<"f-const";}
};
int main(){
   const S sc;
   S s;
   s.f();
   sc.f();
   return 0;
}

第一次打印的输出将是"f"但对于第二个,它将是"f-const"

如果我从结构体中删除not const方法,我将得到两个对象相同的输出。这是因为该函数被称为"最适合",因为它可以为非const对象添加"constiness"。(不能删除const方法,因为它根本不适合…)

在你的代码中有没有显式运算符对于不是const,所以当它寻找"最适合"时,它可以从选项中选择,并采取看起来最好的。你有一个警告,因为有两个适合,但仍然选择其中一个,我不知道为什么一个看起来比另一个更好…但是对于const它有两个显式函数,编译器无法选择何时有显式方法!这就是为什么你会得到一个错误。

如果您想要相同的行为,还可以添加显式非const操作符,如下所示:

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

最新更新