题目
设计一个 Person 类,成员包括:姓名、性别、年龄。需要实现的功能 (成员函数):输入、输出、修改成员,根据有关信息初始化对象。main() 函数先输出把对象初始化为缺省值的结果、再输出修改各成员的结果、再输出经输入函数修改各成员的结果、最后设计一个比较两人年龄的函数,并在 main() 函数中测试之。
相关阅读
相关阅读
完整代码
#include<bits/stdc++.h>
#define Pi 3.14;
using namespace std;
class Person{
string name;
int sex; //1代表男, 0代表女
int age;
public:
Person(){
this->name = "无名氏";
this->sex = -1;
this->age = -1;
}
void input(string name, int sex, int age){
this->name = name;
this->sex = sex;
this->age = age;
}
void output(){
cout << "姓名: " << name << endl;
if (sex == 1)
cout << "性别: 男" << endl;
else if (sex == 0)
cout << "性别: 女" << endl;
else
cout << "性别: 未知" << endl;
if (age >= 0)
cout << "年龄: " << age << endl;
else
cout << "年龄: 未知" << endl;
}
void modifyName(string name){
this->name = name;
}
void modifySex(int sex){
this->sex = sex;
}
void modifyAge(int age){
this->age = age;
}
void compareAge(Person other){
if (age > other.age)
cout << name << "比" << other.name << "大" << endl;
else if (age == other.age)
cout << name << "和" << other.name << "一样大" << endl;
else
cout << name << "比" << other.name << "小" << endl;
}
};
int main(){
Person person1, person2;
cout << "初始化对象为缺省值的结果" << endl;
person1.output();
person1.modifyName("小明");
person1.modifySex(1);
person1.modifyAge(18);
cout << "修改各成员的结果" << endl;
person1.output();
person1.input("小红", 0, 20);
cout << "输入函数修改各成员的结果" << endl;
person1.output();
person2.input("小王", 1, 22);
person1.compareAge(person2);
}