[英]Argument of type “const char **” is incompatible with parameter of type “const char *”
[英]Default argument of type "const char *" is incompatible with parameter of type "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);
}
根據編譯器,可以在只讀內存中分配C樣式的字符串文字。 因此它們是const char[N+1]
( N
是字符串長度) (由於數組到指針衰減,它可以隱式轉換為const char*
) 。
你遇到的問題是刪除const
限定符是非法的(除了臭名昭着的const_cast
或等效的C風格的const_cast
) 。
既然你只是從sir
那里讀書,你可以通過使sir
成為const char*
而不違反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);
}
關於字符串文字 :
在C中,字符串文字的類型為
char[]
,可以直接分配給(非const)char*
。 C ++ 03也允許它(但不贊成它,因為文字在C ++中是const)。 沒有強制轉換,C ++ 11不再允許這樣的賦值。
你的老師可能更精通C或“過時”的C ++。 如上所述,語言(= modern C ++)不允許從字符串文字中賦值/初始化char*
。
解決方法:
使用char const *
作為參數的類型。 當字符串未被修改時,這是合理的解決方案(為什么要修改字符串文字?)
不推薦 。 當你需要寫入該指針時:將字符串文字的(副本)存儲為(非常量) char[]
並引用它。 問題:線程安全; 副作用; 你為什么想做這個??
更好 。 如果需要寫入/更改字符串:use std::string
。
下面是錯誤版本
print_results("C = ", c);
以下是已解決的版本
print_results((char*)"C = ", c);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.