Default argument of type “const char *” is incompatible with parameter of type “char *”

前端 未结 2 605
甜味超标
甜味超标 2021-01-14 09:02

So I got this code from my teacher but it doesn`t work combined with other code, it works only if it is separatly in a project. The whole code works great, less this part

相关标签:
2条回答
  • 2021-01-14 09:17

    Depending on compiler, C-style string literals may be allocated in readonly memory. Thus they are const char[N+1] (N is the string length) (which is implicitly convertible to const char* because of array to pointer decay).

    The problem you're having is that it's illegal to drop const qualifiers (with the exception of the infamous const_cast or equivalent C-style cast).

    Since you're only reading from sir, you can fix this by making sir be const char* instead, which doesn't violate const:

    class student {
    ...
    student(int = 8, const char* =" "); // problem solved
    ...
    };
    
    student::student(int nr_marks, const char* sir) : // remember to change it here as well
        marks(nr_marks)
    {
        strcpy(name, sir);
    }
    
    0 讨论(0)
  • 2021-01-14 09:21

    About string literals:

    In C, string literals are of type char[], and can be assigned directly to a (non-const) char*. C++03 allowed it as well (but deprecated it, as literals are const in C++). C++11 no longer allows such assignments without a cast.

    Your teacher is possibly more versed in C or "dated" C++. As stated above the language (= modern C++) disallows the assignment / initialization of a char* from a string literal.

    Workarounds:

    • Use char const * as type for the parameter. That's the reasonable solution when the string is not modified (why would you modify a string literal??)

    • Not recommended. When you need to write to that pointer: Store (a copy of) the string literal as a (non const) char[] and reference that. Issues: thread safety; side effects; why would you want to do this??

    • Better. If you need to write to / change the string: use std::string.

    0 讨论(0)
提交回复
热议问题