操作符重载和const_cast的使用
operator overloading and the usage of const_cast
对于以下代码片段,
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_cast
从const
成员a
中移除const
,从而允许other.a
的赋值成功(如果没有const_cast
, a
的类型将是const int
,因此它将不可修改)。
可能的想法是a
在类构造时初始化,不能在任何其他地方"按设计"修改,但是类的作者决定为赋值设置一个例外。
我对这段代码有复杂的感觉,通常使用const_cast
是设计不良的症状,另一方面,允许赋值但保留所有其他操作的const
可能是合乎逻辑的。
a是const成员变量。Const_cast (a)绕过了常量正确性规则。否则,只能在构造函数的初始化列表中赋值a。
相关文章:
- 继承函数的重载解析
- 你能重载对象变量名本身返回的内容吗
- 从父命名空间重载类型
- 使用C++中的模板和运算符重载执行矩阵运算
- 为什么这个运算符<重载函数对 STL 算法不可见?
- 如何理解C++标准N3337中的expr.const.cast子句8
- 重载操作程序时出错>>用于类中的字符串 memebr
- 一个关于在C++中重载布尔运算符的问题
- 不同翻译单元中不可重载的非内联函数定义
- 为什么使用SFINAE而不是函数重载
- C++Cast运算符过载
- 为什么我不能在 C++ 中的特定函数重载中调用同一函数的任何其他重载?
- 将重载的成员函数传递给函数模板
- c++:可变模板和函数重载
- 重载元组索引运算符-C++
- 如何使用重载的相等(==)运算符向测试用例添加描述
- 重载==不适用于二进制树
- 为什么Mat类的两个对象可以在不重载运算符+的情况下添加
- 重载运算符new[]的行为取决于析构函数
- 正在尝试重载二进制搜索树分配运算符