Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
833 views
in Technique[技术] by (71.8m points)

c++ - Default argument of type "const char *" is incompatible with parameter of type "char *"

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

"Notes" is an other class which works perfectly

class student
{
    char name[30];
    notes marks;
public:
    student(int = 8, char* =" "); //HERE IS WHERE I GOT THE PROBLEM, AT HIS CHAR*
    ~student();
    void read_name();
    void read_marks();
    void modif_mark(int, double);
    void print();
    void check_marks();
};

/*...
  ...
  ...
*here is a lot of code working great*
  ...
  ...
  ...
*/

student::student(int nr_marks, char* sir) :
    marks(nr_marks)
{
    strcpy_s(name, sir);
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...