问题描述
- 一道简单的OOP题目……不会做……求源程序 半小时内速求……
-
有个虚拟足球俱乐部的球队经济人又新招了5名队员,他写了下面的代码,为新队员建了
一个数组,并输出数组的所有元素。其中字符串是队员的名字,而数字则是队员的年龄。
不过有个队员的名字他竟不记得了(他的名字只好用"???"表示,年龄为0)。
(1)请你为``队员"这种对象定义一个类(队员信息的输出格式自定),使程序能编译通
过(不应通过修改main()函数来完成此要求)。要求每个队员的姓名和年龄都是常量。
int main ( )
{
Member newCommers[5] = { Member( "Zhang San", 22),
Member( "Li Si", 19),
Member( "Wang Wu", 18),
Member ( "Zhao Liu", 24) };
for ( int i=0; i<5; i++)
cout << newCommers[i] << endl;
return 0;
}
(2)经济人在主程序中增加了下面的语句,想通过姓名的拼写来查询队员年龄。请你继
续他的工作,完成程序其他部分。
string name[5] = { "Zhang San", "Li Si",
"Wang Wu", "Zhao Liu",
"Pin Yin" };
MemberList list(newCommers , 5);
for (i=0; i<5; i++)
cout << list[name[i]] << endl;
解决方案
#include <iostream>
#include <string>
using namespace std;
class Member
{
public:
int age;
string name;
Member() { age = 0; name=""; }
Member(string n, int a)
{
name=n;
age=a;
}
friend ostream& operator << (ostream& output, Member& m)
{
if (m.age == 0)
output<<"???"<<endl;
else
output<<m.name<<" "<<m.age<<endl;
return output;
}
};
int main()
{
Member newCommers[5] = { Member( "Zhang San", 22),
Member( "Li Si", 19),
Member( "Wang Wu", 18),
Member( "Zhao Liu", 24) };
for ( int i=0; i<5; i++)
cout << newCommers[i] << endl;
return 0;
}
Zhang San 22
Li Si 19
Wang Wu 18
Zhao Liu 24
???
解决方案二:
另一个问题请先采纳再提供,省得写了半天你跑了。
解决方案三:
#include <iostream>
#include <string>
using namespace std;
class Member
{
public:
int age;
string name;
Member() { age = 0; name=""; }
Member(string n, int a)
{
name=n;
age=a;
}
friend ostream& operator << (ostream& output, Member& m)
{
if (m.age == 0)
output<<"???"<<endl;
else
output<<m.name<<" "<<m.age<<endl;
return output;
}
friend ostream& operator << (ostream& output, Member * m)
{
if (m->age == 0)
output<<"???"<<endl;
else
output<<m->name<<" "<<m->age<<endl;
return output;
}
};
class MemberList
{
private: Member* members;
private: int count;
public: MemberList(Member m[], int c)
{
members=m; count=c;
}
Member* const operator[](const string s)
{
for (int i=0;i<count;i++)
if (members[i].name == s) return &members[i];
return new Member();
}
};
int main()
{
Member newCommers[5] = { Member( "Zhang San", 22),
Member( "Li Si", 19),
Member( "Wang Wu", 18),
Member( "Zhao Liu", 24) };
for ( int i=0; i<5; i++)
cout << newCommers[i] << endl;
string name[5] = { "Zhang San", "Li Si",
"Wang Wu", "Zhao Liu",
"Pin Yin" };
MemberList list(newCommers , 5);
for (int i=0; i<5; i++)
cout << list[name[i]] << endl;
return 0;
}
解决方案四:
http://codepad.org/XF13zSUr
Zhang San 22
Li Si 19
Wang Wu 18
Zhao Liu 24
???
Zhang San 22
Li Si 19
Wang Wu 18
Zhao Liu 24
???
时间: 2024-11-08 20:16:32