casting operator - const vs non-const

不羁的心 提交于 2019-12-30 08:05:13

问题


I have this code sample:

class Number 
{ 
  int i;
  public:
    Number(int i1): i(i1) {}
    operator int() const {return i;}
};

What are the implications of removing the const modifier from the casting operator? Does it affect auto casting, and why?


回答1:


If the conversion operator is not const, you can't convert const objects:

const Number n(5);
int x = n; // error: cannot call non-const conversion operator



回答2:


If you have a function like this:

void f(const Number& n)
{
  int n1 = n;
}

It will start giving compilation error if you remove const in the casting operator.




回答3:


The const version can be called regardless of whether the class Number instance is const or not. If the operator is declared non-const it can only be called on non-const entities - when you try to implicitly use it where it can't be called you'll get a compile error.



来源:https://stackoverflow.com/questions/2325121/casting-operator-const-vs-non-const

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!