设计国家类Country,包含国名(char name[40])、首都(char capital[40])和人口数量(int Population)。根据给定的main函数设计必要的成员函数。
时间: 2024-03-25 19:39:53 浏览: 126
全球国家地区中英文名称含首都代码区号
以下是根据给定的main函数设计的Country类:
```
#include<iostream>
#include<cstring>
using namespace std;
class Country {
private:
char name[40];
char capital[40];
int population;
public:
Country(const char* cou = "Russia", const char* cap = "Moscow", int pop = 143000000);
const char* GetName() const;
const char* GetCapital() const;
int GetPopulation() const;
void Set(const char* cou = "Russia", const char* cap = "Moscow", int pop = 143000000);
void Show();
};
Country::Country(const char* cou, const char* cap, int pop) {
strcpy(name, cou);
strcpy(capital, cap);
population = pop;
}
const char* Country::GetName() const {
return name;
}
const char* Country::GetCapital() const {
return capital;
}
int Country::GetPopulation() const {
return population;
}
void Country::Set(const char* cou, const char* cap, int pop) {
strcpy(name, cou);
strcpy(capital, cap);
population = pop;
}
void Country::Show() {
cout << name << "-" << capital << "-" << population << endl;
}
int main() {
Country c1;
cout << "Show object c1:";
cout << c1.GetName() << "-" << c1.GetCapital() << "-" << c1.GetPopulation() << endl;
char name[40], capital[40];
int population;
cin >> name >> capital >> population;
Country c2(name, capital, population);
cout << "Show object c2:";
cout << c2.GetName() << "-" << c2.GetCapital() << "-" << c2.GetPopulation() << endl;
cin >> name >> capital >> population;
cout << "Reset and Show object c1:";
c1.Set(name, capital, population);
c1.Show();
cout << "Reset and Show object c2:";
c2.Set();
c2.Show();
return 0;
}
```
在该类中,我们将国名、首都和人口数量分别用char数组、char数组和int类型来表示,并提供了构造函数、获取成员变量的函数、设置成员变量的函数和展示成员变量的函数。其中,构造函数和设置成员变量的函数都提供了默认参数,使得在创建对象时可以不提供参数。
阅读全文