c++无法将参数 2 从const char [9]转换为char *
***原因应该是函数的实参与形参类型不匹配, 字符串在内存中是一个常量字符串数组,因此在函数中的形参也应当加上const关键字才行。
#include "pch.h"
#include <iostream>
#include<cstring>
using namespace std;
class Student {
public:
Student() {
this->id = 0;
this->name = NULL;
}
Student(int id, const char *name) {//如果这里不加const,那么将报错无法将参数 2 从“const char [9]”转换为“char *”
this->id = id;
int len = strlen(name);
this->name = new char[len+1];
strcpy_s(this->name, len + 1, name);
}
Student(const Student &another) {
this->id = another.id;
int len = strlen(another.name);
this->name = new char[len + 1];
strcpy_s(this->name,len+1 ,another.name);
}
void printS() {
cout << this->name<<endl;
}
~Student() {
if (this->name != NULL) {
delete[]this->name;
this->name = NULL;
this->id = 0;
}
}
private:
int id;
char *name;
};
int main() {
Student s1(1, "zhagnsan");
Student s2 = s1;
s1.printS();
s2.printS();
return 0;
}
原因应该是函数的实参与形参类型不匹配, 字符串在内存中是一个常量字符串数组,因此在函数中的形参也应当加上const关键字才行。