“const char \*”类型的默认参数与“char \*”类型的参数不兼容

新手上路,请多包涵

所以我从我的老师那里得到了这个代码,但它不能与其他代码结合使用,它只有在它单独在一个项目中时才有效。整个代码效果很好,少了这部分

“Notes”是另一个完美运行的类

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

原文由 Iulian B. 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 643
1 个回答

根据编译器,C 风格的字符串文字可能会分配在只读内存中。因此它们是 const char[N+1] N 是字符串长度) (由于数组到指针的衰减,它可以隐式转换为 const char*

您遇到的问题是丢弃 const 限定符是非法 的(臭名昭著的 const_cast 或等效的 C 样式转换除外)

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

原文由 Cruz Jean 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题