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 12:39:39 浏览: 87
这段代码有两个问题:
1. 在类的成员函数中,函数的返回类型和const关键字位置写反了,应该将const关键字放在函数返回类型的左侧。
2. 在类的成员函数中,char*类型的成员函数GetName和GetCapital返回的是类的私有成员变量指针,这样会导致类的私有成员变量被意外修改,应该将返回类型改为const char*。
修正后的代码如下所示:
```
class Country {
private:
char name[40], capital[40];
int population;
public:
Country(const char* cou = NULL, const char* cap = "NONE", int pop = 0);
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;
}
```
阅读全文