在visual_studio中想做一个[]重载的小练习,
#include <cstring>
#include <iostream>
using namespace std;
struct Person
{
double salary;
char *name;
};
class SalaryManage
{
private:
Person *employ;
int max;
int n;
public:
SalaryManage(int Max = 0)
:max(Max),n(0),employ(new Person[max])
{
}
double &operator[](char *Name)
{
Person *p;
for (p = employ;p < employ + n;p++)
if (strcmp(p->name, Name) == 0)
return p->salary;
p = employ + n++;
p->name = new char[strlen(Name) + 1];
strcpy(p->name, Name);
p->salary = 0;
return p->salary;
}
void display()
{
for (int i = 0;i < n;i++)
cout << employ[i].name << " " << employ[i].salary << endl;
}
~SalaryManage()
{
delete[] employ;
}
};
int main()
{
SalaryManage s(3);
s["张三"] = 2188.88;
s["里斯"] = 1234.65;
s["王五"] = 3200.98;
cout << "张三\t" << s["张三"] << endl;
cout << "里斯\t" << s["里斯"] << endl;
cout << "王五\t" << s["王五"] << endl;
s.display();
}
可是主函数部分显示
作为C++新手,请大佬们帮忙指点一二
double &operator[](const char *Name)
注意 const 。
C++ 里,字符串字面量是常量字符串,不能匹配
char *
参数,只能用const char *
。