c++ - 为什么指针仍然可以修改函数内部的 const 引用对象?
问题描述
假设我有这样的学生课:
class Student {
private:
std::string _name;
public:
Student(const std::string&);
void setName(const std::string&);
const std::string& getName() const;
};
还有一个类似的功能:
void changeConstRefObj(const Student& student){
std::string newName = ....;
student.setName(newName);
}
调用时无效setName
。但是您仍然可以使用指针来调用setName
(不使用static_cast
,可能是编译器有问题?),如下所示:
void changeConstRefObj(const Student& student)
{
std::string newName = ...;
Student *p = (Student*)(&student);
p->setName(newName);
}
或者使用下面这样的新对象(我不知道它为什么起作用)。
void changeConstRefObj(const Student& student)
{
std::string newName = ...;
Student t(newName);
Student *p = (Student*)(&student);
*p = t;
}
我认为如果我使用 const 我将无法更改对象,但通过指针我可以轻松更改它。为什么会这样?
解决方案
推荐阅读
- javascript - 如何在 Flow 中正确输入渲染道具?
- python - 为 python smtplib 获取“网络无法访问”
- r - 在与 map_df 循环中的其他表堆叠之前将 HTML_tables 转换为字符
- oauth-2.0 - 使用 Azure AD 通过 OAuth2 对 Azure API 管理进行身份验证
- html - Ajax,旧值先出现,然后新值出现
- php - 分页在laravel中以不同的方式产生
- javascript - 如何接收字符串并将其解析为浮点数?
- javascript - 基于类似二叉搜索树的算法拟合数组
- php - PHP DOMElement::replaceChild 产生致命错误
- reactjs - 从 Kafka 获取消息,发送到 Rsocket 并从 React 客户端接收