C++类与指针练习报错:const char*与char*类型不兼容问题求助
解决C++类中字符数组与字符串字面量的类型不兼容错误
错误原因
字符串字面量(如"kia"、"red")在C中属于const char*类型,而你的setName和setColor函数参数声明为char[](编译器会将其视为char*)。C禁止将const char*隐式转换为char*——这是为了防止代码修改只读内存中的字符串字面量,违反常量安全性。
方案一:修改函数参数为const char*
直接调整setName和setColor的参数类型,使其兼容字符串字面量,strcpy_s可以正常处理const char*类型的输入:
修改后的成员函数代码:
void setName(const char* n) { strcpy_s(name, n); } void setColor(const char* n) { strcpy_s(color, n); }
(写成const char n[]效果完全一致,只是const char*的写法更直观)
方案二:改用std::string替代字符数组(推荐)
在C++中,std::string比原生字符数组更安全、易用,无需手动管理内存和长度,从根源避免这类类型匹配问题:
完整修改后的代码:
#include <iostream> #include <string> using namespace std; class car { private: string name; string color; int maxspeed; int model; public: void setName(const string& n) { name = n; } void setColor(const string& n) { color = n; } void setMaxspeed(int m) { maxspeed = m; } void setModel(int m) { model = m; } const string& getName() const { return name; } const string& getColor() const { return color; } int getMaxspeed() const { return maxspeed; } int getModel() const { return model; } void print() const { cout << "name = " << name << "\n" << "color = " << color << "\n" << "Maxspeed = " << maxspeed << "\n" << "Model = " << model << "\n"; } }; int main() { car x; x.setName("kia"); x.setColor("red"); x.setMaxspeed(300); x.setModel(2017); x.print(); return 0; }
注:这里将getter函数和print声明为const,符合C++的const正确性原则——这些函数不会修改类成员。
内容的提问来源于stack exchange,提问作者Omar Hossam
相关产品推荐
相关产品推荐

