首页 > 解决方案 > 为什么我能够更改作为常量引用传递的对象的成员?

问题描述

class Student {
private:
    int age;
public:
    char *name;
    Student(int age,char*name) {
        this->age=age;
        this->name=new char[strlen(name)+1];
        strcpy(this->name,name);
    }
    Student(Student const &s1) {
        this->age=s1.age;
        this->name=new char[strlen(s1.name)+1];
        strcpy(this->name,s1.name);
        s1.name[0]='x';
    }
    void display() {
        cout<<age<<" "<<name<<endl;
    }
};
int main() {
    char name[]="abcd";
    Student s1(10,name);
    s1.display();
    Student s2(s1);
    s2.name[0]='x';
    s1.display();
    s2.display();
}

我已将 s1 作为常量引用传递,但我能够更改 s1.name[0] 并且程序编译成功。为什么我可以更改 s1.name[0]?在此处输入图像描述

标签: c++oop

解决方案


你没有修改s1. 您修改了一些不相关的内存块(由 分配new),其中s1包含一个指针。在 C++ 中,原始指针与其可能指向的任何内存块之间没有特殊关系。

如果您使用std::string而不是原始指针和手动内存管理,则不会出现此问题。


推荐阅读