why the warining deprecated conversion from string constant to 'char*' occured in the bellow program [duplicate]

牧云@^-^@ 提交于 2021-02-11 12:29:23

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!