问题
I created a class called person with the public member function fill_data which takes two arguments as char array and int . I passed the arguments like this fill_data("tushar",30); but there shows a warning deprecated conversion from string constant to 'char*' but I don't understand why, if any help me to know |
#include<iostream>
#include<cstring>
using namespace std;
class person
{
char name[20];
int age;
public:
void fill_data(char name2[],int age2)
{
strcpy(name,name2);
age=age2;
}
void display_data(void)
{
cout<<name<<endl;
cout<<age<<endl;
}
};
int main()
{
person p1;
p1.fill_data("tushar",30);
p1.display_data();
return 0;
}
回答1:
You passed the string constant "tushar" to the function parameter char name2[], which is non-const. So in order to do this, the compiler had to convert the string constant to a char * (versus a const char *), which is deprecated.
If fill_data is not going to modify name2, the parameter should be const. If fill_data is going to modify whatever is passed as the name2 parameter, don't pass it a constant like "tushar".
Make up your mind and code one or the other.
来源:https://stackoverflow.com/questions/56522654/why-the-warining-deprecated-conversion-from-string-constant-to-char-occured-i