C++ 字符串常量赋值警告:ISO C++ forbids converting a string constant to ‘char*’ [-Wwrite-strings]
解决 C++ 字符串常量赋值警告:ISO C++ forbids converting a string constant to ‘char*’ [-Wwrite-strings]
在 C++ 中,将字符串常量直接赋值给 char* 指针是不安全的,因为字符串常量是不可修改的,这会导致编译器发出 'ISO C++ forbids converting a string constant to ‘char*’ [-Wwrite-strings]' 警告。
为了解决这个问题,可以使用以下两种方法:
- 使用
const char*指针: 将字符串常量赋值给const char*指针,表示该指针指向的数据是不可修改的。 - 使用
std::string类型: 使用std::string类型来存储字符串,它可以安全地处理字符串常量,并提供更方便的字符串操作方法。
以下是使用 const char* 修正后的代码示例:
#include <iostream>
#include <cstring>
class MyString {
private:
char* data;
public:
MyString(const char* str) {
data = new char[strlen(str) + 1];
strcpy(data, str);
}
~MyString() {
delete[] data;
}
const char* getData() const {
return data;
}
};
int main() {
const char* str = 'hello';
MyString str1 = str;
std::cout << str1.getData() << std::endl;
return 0;
}
在这个示例中,我们使用 const char* 接收字符串常量 'hello',并在 MyString 类的构造函数中动态分配内存来存储字符串的副本。
使用 std::string 可以更简洁地实现相同的功能,例如:
#include <iostream>
#include <string>
int main() {
std::string str1 = 'hello';
std::cout << str1 << std::endl;
return 0;
}
建议优先使用 std::string 来处理字符串,因为它更加安全和方便。
原文地址: https://www.cveoy.top/t/topic/Uq4 著作权归作者所有。请勿转载和采集!