首页 > 解决方案 > 为什么指针仍然可以修改函数内部的 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 我将无法更改对象,但通过指针我可以轻松更改它。为什么会这样?

标签: c++

解决方案


推荐阅读