使用strcpy()赋值char数组报错:无法将char**转换为char*的问题排查
问题排查与代码修正:char**转char*错误处理
错误原因
- 核心问题是员工类中
E_Name的类型定义错误:你将其声明为char* E_Name[30],这是一个包含30个字符指针的数组(本质是char**类型),但实际需求是存储员工姓名的字符数组,应该定义为char E_Name[30]。 strcpy函数要求两个参数均为char*类型,错误的类型导致传入了char**,触发类型转换错误。- 学校电脑的旧编译器(如老版VC++)对类型检查宽松,未拦截该错误,但标准C++不允许这种不匹配操作。
- 额外问题:默认构造函数中
PId = 0;是笔误,应为E_Id = 0;;析构函数中Obeject拼写错误,应为Object。
修正后的完整代码
#include<iostream> using namespace std; #include<conio.h> #include<string.h> class Employee{ int E_Id; char E_Name[30]; // 修正:改为字符数组 int No_Hours; int Rate_Hour; public: // 修正参数类型为const char*,符合字符串传递规范 void SetData(int Id, const char* Name, int Hours, int Rate) { E_Id = Id; strcpy(E_Name, Name); No_Hours = Hours; Rate_Hour = Rate; } void DispData() { cout<<"Employee ID: "<<E_Id<<endl; cout<<"Employee Name: "<<E_Name<<endl; cout<<"Number of Hours: "<<No_Hours<<endl; cout<<"Rate per Hour: "<<Rate_Hour<<endl; } void InputData() { cout<<"Give Employee ID: "; cin>>E_Id; cout<<"Give Employee Name: "; cin>>E_Name; // 现在正确,字符数组可直接接收输入 cout<<"Give Number of Hours: "; cin>>No_Hours; cout<<"Give Rate per Hour: "; cin>>Rate_Hour; } int GetEId() { return E_Id; } // 修正返回类型,返回字符数组的指针 const char* GetEName() { return E_Name; } int GetNoHours() { return No_Hours; } int GetRateHour() { return Rate_Hour; } Employee() { E_Id = 0; // 修正笔误 strcpy(E_Name, ""); No_Hours = 0; Rate_Hour = 0; } // 修正参数类型为const char* Employee(int Id, const char* Name, int Hours, int Rate) { E_Id = Id; strcpy(E_Name, Name); No_Hours = Hours; Rate_Hour = Rate; } ~Employee() { cout<<"Object Destroyed"<<endl; // 修正拼写错误 } }; int main() { Employee* e; e = new Employee[10]; int i; cout<<"Give Data"<<endl; for(i=0;i<10;i++) { (e+i)->InputData(); } // 优化:直接计算薪资,避免重复调用函数 int high = (e+0)->GetNoHours() * (e+0)->GetRateHour(); int loc = 0; for(i=1;i<10;i++) // 从i=1开始,减少一次重复计算 { int currentSalary = (e+i)->GetNoHours() * (e+i)->GetRateHour(); if(currentSalary > high) { high = currentSalary; loc = i; } } cout<<"Employee with Highest Salary"<<endl; (e+loc)->DispData(); delete[] e; getch(); return 0; }
额外优化说明
- 将
SetData和构造函数的姓名参数改为const char*,符合C++字符串传递规范,避免修改传入的字符串常量。 - 薪资计算循环从
i=1开始,减少一次重复计算,提升效率。
内容的提问来源于stack exchange,提问作者Syed Baqir Hassan Naqvi
相关产品推荐
相关产品推荐

