有关指针的错误使用
错误名称:[Warning] deprecated conversion from string constant to ‘char*’ [-Wwrite-strings]
故障代码如下:
#include <iostream>
#include <cstring>
using namespace std;
class Student{
private:
char num[20];
char name[20];
int age;
public:
Student(char * num,char name[], int age) { //问题出现在这里
strcpy(this->num, num);
strcpy(this->name, name);
this->age = age;
}
void show() {
cout << "num = " << this->num << " name = " << this->name << " age = " << this->age << endl;
}
};
int main(void) {
Student * student = new Student("0504020101", "张三", 20);
student->show();
}
原因分析:通过主函数中构造方法,给对象student赋了初值,前两个赋值是字符常量,由构造方法中字符数组接收。 由于传递过去的是常量,无法改变其值,而构造方法中的前两个参数为字符数组变量,接收不变的常量会有警告。整型数据就没有这种情况,整型可以直接用常量赋值,而不用加const
解决方法:在构造方法前两个参数前面加上const关键字。
Student(const char * num,const char name[], int age) {
运行结果:
编译并成功运行