cast operator - const vs non-const

Ami*_*rad 14 c++ casting const operator-overloading

我有这个代码示例:

class Number 
{ 
  int i;
  public:
    Number(int i1): i(i1) {}
    operator int() const {return i;}
};
Run Code Online (Sandbox Code Playgroud)

const从铸造操作符中删除修饰符有什么含义?它会影响汽车铸造,为什么?

Ash*_*ain 28

如果转换运算符不是const,则无法转换const对象:

const Number n(5);
int x = n; // error: cannot call non-const conversion operator
Run Code Online (Sandbox Code Playgroud)


sha*_*oth 5

const无论class Number实例是否为const ,都可以调用该版本.如果运算符被声明为非const,则只能在非const实体上调用 - 当您尝试隐式使用它时无法调用它将导致编译错误.


Nav*_*een 5

如果你有这样的功能:

void f(const Number& n)
{
  int n1 = n;
}
Run Code Online (Sandbox Code Playgroud)

如果在转换操作符中删除const,它将开始给出编译错误.