Skip to content

Commit e4cf085

Browse files
authored
Update 中括号重载.cpp
1 parent 1ca9bce commit e4cf085

File tree

1 file changed

+48
-41
lines changed

1 file changed

+48
-41
lines changed

practical_exercises/key_exercises/中括号重载.cpp

Lines changed: 48 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -1,51 +1,58 @@
1-
//Eg8-9.cpp
21
#include <iostream>
32
#include <cstring>
43
using namespace std;
5-
struct Person{ //职工基本信息的结构
6-
double salary;
7-
char *name;
4+
struct Person
5+
{ //职工基本信息的结构
6+
double salary;
7+
char *name;
88
};
9-
class SalaryManaege{
10-
Person *employ; //存放职工信息的数组
11-
int max; //数组下标上界
12-
int n; //数组中的实际职工人数
9+
class SalaryManaege
10+
{
11+
Person *employ; //存放职工信息的数组
12+
int max; //数组下标上界
13+
int n; //数组中的实际职工人数
1314
public:
14-
SalaryManaege(int Max=0){
15-
max=Max;
16-
n=0;
17-
employ=new Person[max];
18-
}
19-
//返回引用特性是可以直接在放在左值,直接使用
20-
double &operator[](char *Name) { //重载[],返回引用
21-
Person *p;
22-
for(p=employ;p<employ+n;p++)
23-
//如果存在处理
24-
if(strcmp(p->name,Name)==0)
25-
return p->salary;
26-
//不存在情况处理
27-
p=employ + n++;
28-
p->name=new char[strlen(Name)+1];
29-
strcpy(p->name,Name);
30-
p->salary=0;
31-
return p->salary;
32-
}
15+
SalaryManaege(int Max = 0)
16+
{
17+
max = Max;
18+
n = 0;
19+
employ = new Person[max];
20+
}
21+
//返回引用特性是可以直接在放在左值,直接使用
22+
double &operator[](char *Name)
23+
{ //重载[],返回引用
24+
Person *p;
25+
for (p = employ; p < employ + n; p++)
26+
//如果存在处理
27+
if (strcmp(p->name, Name) == 0)
28+
return p->salary;
29+
//不存在情况处理
30+
p = employ + n++;
31+
p->name = new char[strlen(Name) + 1];
32+
strcpy(p->name, Name);
33+
p->salary = 0;
34+
return p->salary;
35+
}
3336

34-
void display(){
35-
for(int i=0;i<n;i++)
36-
cout<<employ[i].name<<" "<<employ[i].salary<<endl;
37-
}
37+
void display()
38+
{
39+
for (int i = 0; i < n; i++)
40+
cout << employ[i].name << " " << employ[i].salary << endl;
41+
}
42+
~SalaryManaege() {
43+
delete employ;
44+
}
3845
};
39-
int main(){
46+
int main()
47+
{
4048
SalaryManaege s(3);
41-
s["张三"]=2188.88;
42-
s["里斯"]=1230.07;
43-
s["王无"]=3200.97;
44-
cout<<"张三\t"<<s["张三"]<<endl; cout<<"里斯\t"<<s["里斯"]<<endl;
45-
cout<<"王无\t"<<s["王无"]<<endl;
46-
47-
cout<<"-------下为display的输出--------\n\n";
49+
s["张三"] = 2188.88;
50+
s["里斯"] = 1230.07;
51+
s["王无"] = 3200.97;
52+
cout << "张三\t" << s["张三"] << endl;
53+
cout << "里斯\t" << s["里斯"] << endl;
54+
cout << "王无\t" << s["王无"] << endl;
55+
56+
cout << "-------下为display的输出--------\n\n";
4857
s.display();
49-
system("pause");
5058
}
51-

0 commit comments

Comments
 (0)