class Country { private: char name[40],capital[40]; int population; public: Country( const char* cou=NULL,const char* cap=NONE,int pop=0 ); char GetName 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; } char Country::GetName const( ) { return name; } 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; } 这段代码是否有问题
时间: 2024-03-25 19:39:30 浏览: 73
这段代码存在一些问题:
1. 在构造函数 Country 和函数 GetName、GetCapital 中,返回的类型应该是 char* 而不是 char,因为成员变量 name 和 capital 都是 char 数组,需要返回数组首地址。
2. 在函数的参数列表中,出现了未定义的变量 NONE、Russia,应该改为字符串常量 "NONE" 和 "Russia"。
修改后的代码如下:
```
class Country {
private:
char name[40], capital[40];
int population;
public:
Country(const char* cou = NULL, const char* cap = "NONE", int pop = 0);
char* GetName() 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;
}
char* Country::GetName() const {
return name;
}
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;
}
```
阅读全文