c++ - 为什么我能够更改作为常量引用传递的对象的成员?
问题描述
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]?在此处输入图像描述
解决方案
你没有修改s1
. 您修改了一些不相关的内存块(由 分配new
),其中s1
包含一个指针。在 C++ 中,原始指针与其可能指向的任何内存块之间没有特殊关系。
如果您使用std::string
而不是原始指针和手动内存管理,则不会出现此问题。
推荐阅读
- c# - C#在循环中动态调用函数
- typescript - 如何在抽象类或接口中正确描述/转换打字稿多态自我
- orocommerce - oro commerce - 通过api添加多个产品
- python - Jupyter 中没有名为“casADI”的模块
- google-cloud-sql - 如何解决 CloudSQL 中的复制错误
- sql - 在 SQL 中给出意外输出的两个字段的商的 AVG()
- python - 在从 github 上传的 Elastic Beanstalk 中运行 Python 文件
- angular - 模态页面中的离子标签(@ionic/angular)
- javascript - 为什么我无法在 google、yahoo 和 bing 搜索中索引我的 react-app?
- javascript - Chrome 扩展 javascript