【发布时间】:2015-04-09 07:08:02
【问题描述】:
在我在网上找到的以下示例中,提到const_cast 的优点之一是它允许常量函数更改类成员。这对我来说是一个问题。为什么我们要通过const 为函数设置规则,然后用const_cast 打破该规则?是不是跟作弊一样?完全不为函数设置const不是更好吗?
#include <iostream>
using namespace std;
class student
{
private:
int roll;
public:
student(int r):roll(r) {}
// A const function that changes roll with the help of const_cast
void fun() const
{
( const_cast <student*> (this) )->roll = 5;
}
int getRoll() { return roll; }
};
int main(void)
{
student s(3);
cout << "Old roll number: " << s.getRoll() << endl;
s.fun();
cout << "New roll number: " << s.getRoll() << endl;
return 0;
}
【问题讨论】:
-
有趣的是getter不是
const。 -
C++ 提供了很多方法让自己在脚上开枪,这就是其中之一。
-
我认为 const_cast 的主要理由之一是能够调用未正确将其参数声明为 const 的旧 C API 函数(通常是指向 const 的指针)。这将使这些 API 无法从 const 方法调用(对 const 成员进行操作)。但是您可能知道该函数不会更改其参数(例如 strcmp)。 const_cast 可以让你去掉 const 以便能够使用该函数。
标签: c++ c++11 const-cast