运算符重载和 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;
意思是?或者为什么这个运算符要这样定义?换句话说,我对它的用法和它的定义/编写方式感到困惑。
For the following code snippet,
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;
}
what do the lines of
A & A::operator =(const A &other)
const_cast<int&>(a) = other.a;
mean? Or why this operator is defined this way? In other words, I feel confused about its usage and the way it is defined/written.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
const_cast
从const
成员a
中删除const
,从而允许从other.a 进行赋值
才能成功(如果没有const_cast
,a
的类型将为const int
,因此它不可修改)。可能的想法是
a
在类构造时初始化,并且不能在任何其他地方“按设计”进行修改,但该类的作者决定对赋值进行例外处理。我对这段代码有复杂的感觉,使用 const_cast 通常是糟糕设计的症状,另一方面,允许赋值但保留 const 也是合乎逻辑的。 /code> 用于所有其他操作。
The
const_cast
removes theconst
from theconst
membera
, thus allowing the assignment fromother.a
to succeed (without theconst_cast
the type ofa
would beconst int
, and thus it wouldn't be modifiable).Probably the idea is that
a
is initialized at class construction and can't be modified "by design" in any other place, but the author of the class decided to make an exception for assignment.I have mixed feelings against this piece of code, very often the use of a
const_cast
is a symptom of bad design, on the other hand it can be logical to allow assignment but retain theconst
for all the other operations.a 是一个 const 成员变量。 const_cast(a) 绕过 const -正确性规则。否则,您只能在构造函数的初始值设定项列表中分配 a 。
a is a const member variable. const_cast(a) bypasses the const-correctness rules. Otherwise, you could only assign a in the initializer list of the constructor.