运算符重载和const_cast的用法

时间:2011-09-14 21:29:29

标签: c++ operator-overloading const

对于以下代码段,

class A{
  const int a;
  public:
  A(): a(0){}
  A(int m_a):a(m_a){};
  A& operator =(const A &other);
};
A & A::operator =(const A &other)
{
  const_cast<int&>(a) = other.a;
  return *this;
}

的内容是什么?
A & A::operator =(const A &other)

const_cast<int&>(a) = other.a;

意思?或者为什么这个运算符是这样定义的?换句话说,我对它的用法及其定义/编写方式感到困惑。

2 个答案:

答案 0 :(得分:2)

const_castconst成员const中删除了a,从而允许other.a的分配成功(没有const_cast a的类型为const int,因此无法修改。

可能的想法是a在类构造中初始化,并且不能在任何其他地方“按设计”修改,但是该类的作者决定为赋值做出例外。

我对这段代码感到复杂,经常使用const_cast是设计不良的症状,另一方面,允许分配但保留const是合乎逻辑的。对于所有其他操作。

答案 1 :(得分:0)

a是一个const成员变量。 const_cast(a)绕过const正确性规则。否则,您只能在构造函数的初始化列表中指定一个。

相关问题