帮我找以下c++代码的bug:#include<iostream> #include<cstring> using namespace std; class Employee { private: long num; string name; char sex[4]; const char* sect; int wage; static int count; static long totalWage; public: Employee(long n,string nam,char se[4],const char* sec,int wag); void print(); static void ShowStatic(); }; Employee::Employee (long n,string nam,char se[4],const char* sec,int wag) { num=n; name=nam; strcpy(sex,se); sect=new char[strlen(sec)+1]; strcpy(sect,sec); wage=wag; count++; totalWage+=wag; } void Employee::ShowStatic() { cout<<count<<" "<<totalWage<<endl; } void Employee::print() { cout<<num<<" "<<name<<" "<<sex[4]<<" "<<sect<<" "<<wage<<endl; } int main () { int count=0; long totalWage=0; Employee a[2]={Employee(123,"dsb","nan","bzd",2023),Employee(234,"xsb","nv","bzd",2024)}; a[0].print(); a[1].print(); a[0].ShowStatic(); return 0; }
时间: 2023-12-03 11:47:27 浏览: 112
vc++2008编译不了#include<iostream.h>头文件
4星 · 用户满意度95%
在类定义中,静态数据成员 count 和 totalWage 必须在类外进行初始化。
在 main 函数中,变量 count 和 totalWage 与类中的同名静态数据成员重名,造成了混淆。
以下是修正后的代码:
```
#include<iostream>
#include<cstring>
using namespace std;
class Employee {
private:
long num;
string name;
char sex[4];
const char* sect;
int wage;
static int count;
static long totalWage;
public:
Employee(long n,string nam,char se[4],const char* sec,int wag);
void print();
static void ShowStatic();
};
int Employee::count = 0; // 静态数据成员初始化
long Employee::totalWage = 0;
Employee::Employee (long n,string nam,char se[4],const char* sec,int wag) {
num=n;
name=nam;
strcpy(sex,se);
sect=new char[strlen(sec)+1];
strcpy(sect,sec);
wage=wag;
count++;
totalWage+=wag;
}
void Employee::ShowStatic() {
cout<<count<<" "<<totalWage<<endl;
}
void Employee::print() {
cout<<num<<" "<<name<<" "<<sex<<" "<<sect<<" "<<wage<<endl;
}
int main () {
Employee a[2]={Employee(123,"dsb","nan","bzd",2023),Employee(234,"xsb","nv","bzd",2024)};
a[0].print();
a[1].print();
Employee::ShowStatic(); // 静态成员函数调用
return 0;
}
```
修改后的代码中,静态数据成员 count 和 totalWage 在类外进行初始化,避免了混淆。在 main 函数中,使用 Employee::ShowStatic() 调用静态成员函数。
阅读全文