操作符重载和const_cast的使用

operator overloading and the usage of const_cast

本文关键字:cast 重载 const 操作符      更新时间:2023-10-16

对于以下代码片段,

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;

的意思吗?或者为什么这个算子是这样定义的?换句话说,我对它的用法和它的定义/书写方式感到困惑。

const_castconst成员a中移除const,从而允许other.a的赋值成功(如果没有const_cast, a的类型将是const int,因此它将不可修改)。

可能的想法是a在类构造时初始化,不能在任何其他地方"按设计"修改,但是类的作者决定为赋值设置一个例外。

我对这段代码有复杂的感觉,通常使用const_cast是设计不良的症状,另一方面,允许赋值但保留所有其他操作的const可能是合乎逻辑的。

a是const成员变量。Const_cast (a)绕过了常量正确性规则。否则,只能在构造函数的初始化列表中赋值a。