转换操作符 - 常量vs非常量 [英] casting operator - const vs non-const

查看:100
本文介绍了转换操作符 - 常量vs非常量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个代码示例:

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

删除 const 修饰符从铸造操作员?
它会影响自动转换,为什么?

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

推荐答案

如果转换运算符不是常数,转换const对象:

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

这篇关于转换操作符 - 常量vs非常量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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