在寫 C 語言時
char *week[] = {
"Friday",
"Saturday",
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday"
};
是沒問題的,
但是在寫 C++ 時,
char *week[] = {
"Friday",
"Saturday",
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday"
};
卻會跑出警告:
test.cpp:2:3: warning: ISO C++ forbids converting a string constant to ‘char*’ [-Wwrite-strings]
2 | "Friday",
| ^~~~~~~~
test.cpp:3:3: warning: ISO C++ forbids converting a string constant to ‘char*’ [-Wwrite-strings]
3 | "Saturday",
| ^~~~~~~~~~
test.cpp:4:3: warning: ISO C++ forbids converting a string constant to ‘char*’ [-Wwrite-strings]
4 | "Sunday",
| ^~~~~~~~
test.cpp:5:3: warning: ISO C++ forbids converting a string constant to ‘char*’ [-Wwrite-strings]
5 | "Monday",
| ^~~~~~~~
test.cpp:6:3: warning: ISO C++ forbids converting a string constant to ‘char*’ [-Wwrite-strings]
6 | "Tuesday",
| ^~~~~~~~~
test.cpp:7:3: warning: ISO C++ forbids converting a string constant to ‘char*’ [-Wwrite-strings]
7 | "Wednesday",
| ^~~~~~~~~~~
test.cpp:8:3: warning: ISO C++ forbids converting a string constant to ‘char*’ [-Wwrite-strings]
8 | "Thursday"
| ^~~~~~~~~~
解決方法:加上 const
就可以了
const char *week[] = {
"Friday",
"Saturday",
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday"
};
參考資料:
https://blog.csdn.net/whatday/article/details/106267398