C++ 为什么指针仍然可以在函数中修改常量引用对象?

C++ 为什么指针仍然可以在函数中修改常量引用对象?,c++,C++,假设我有这样的学生课: 班级学生{ 私人: std::string _name; 公众: 学生(const std::string&); void setName(const std::string&); 常量std::string&getName()常量; }; 还有一个函数,类似于: void changefonstrefbj(const Student和Student){ std::string newName=。。。。; student.setName(newName); } 调用s

假设我有这样的学生课:

班级学生{
私人:
std::string _name;
公众:
学生(const std::string&);
void setName(const std::string&);
常量std::string&getName()常量;
};
还有一个函数,类似于:

void changefonstrefbj(const Student和Student){
std::string newName=。。。。;
student.setName(newName);
}
调用
setName
时无效。但您仍然可以使用指针来调用
setName
(它不使用
static\u cast
,编译器可能有问题?)

void changefonstrefbj(const Student和Student)
{
std::string newName=。。。;
学生*p=(学生*)(&Student);
p->setName(newName);
}
或者使用像下面这样的新对象(我不知道它为什么工作)

void changefonstrefbj(const Student和Student)
{
std::string newName=。。。;
学生t(新姓名);
学生*p=(学生*)(&Student);
*p=t;
}

我想,如果我使用const,我将无法更改对象,但通过指针,我可以轻松地更改它。为什么会是这样?

我认为如果我使用const,我就无法更改object
正确
但是通过指针我可以很容易地改变它。
因为你丢弃了常量。这就是为什么C风格的强制转换(至少对于指针和引用)是不安全的…关键字
const
可以帮助你避免犯错误;这并不意味着你不能击败它(通过使用
const\u cast(&student)
,或者你的例子中的C风格的cast来抛弃const),并且不管怎样,如果你真的想犯这些错误的话。俗话说,
const
是为了保护你不受墨菲的伤害,而不是马基雅维利的伤害。值得一提的是,即使这样,这也是一种未定义的行为。C++允许假定声明的代码>代码> const 不会改变,因此编译器可以自由地围绕这个事实进行优化,这不使用<代码> StistaCase——误导(最好是指代码> const Studio这里,作为<代码> StistalCase< <代码>不能删除<代码> const )。您的代码使用了,它可以完成const\u cast所能做的任何事情,以及更多。