class Student { private: int Id,score; char name[9]; public: Student( int id=10000,const char* n=NULL,int s=0 ); int GetId(); char* GetName(); int GetScore(); void Set(int id = 99999, const char* n = "NONAME", int s = 100); void Show(); }; Student::Student( int id,const char* n,int s ) { Id=id; score=s; strcpy(name,n); } int Student::GetId() { return Id; } int Student::GetScore() { return score; } char* Student::GetName() { return name; } void Student::Set( int id,const char* n,int score ) { Id=id; score=s; strcpy(name,n); } void Student::Show() { cout<<Id<<"-"<<name<<"-"<<score<<endl;}将上述代码进行修改,成员数据不变
时间: 2024-03-23 12:40:13 浏览: 88
实验二:面向对象C++程序设计.docx
修改后的代码如下:
```cpp
class Student {
private:
int Id, score;
char name[9];
public:
Student(int id = 10000, const char* n = NULL, int s = 0);
int GetId() const;
const char* GetName() const;
int GetScore() const;
void Set(int id = 99999, const char* n = "NONAME", int s = 100);
void Show() const;
};
Student::Student(int id, const char* n, int s) {
Id = id;
score = s;
if (n == NULL) {
strcpy(name, "NONAME");
} else {
strncpy(name, n, 8); // 限制拷贝长度为8
name[8] = '\0'; // 添加字符串结尾标识符
}
}
int Student::GetId() const {
return Id;
}
int Student::GetScore() const {
return score;
}
const char* Student::GetName() const {
return name;
}
void Student::Set(int id, const char* n, int score) {
Id = id;
this->score = score;
if (n == NULL) {
strcpy(name, "NONAME");
} else {
strncpy(name, n, 8);
name[8] = '\0';
}
}
void Student::Show() const {
cout << Id << "-" << name << "-" << score << endl;
}
```
主要的修改有:
1. 在成员函数的声明和定义中增加 const 修饰符,表示这些函数不会修改类的成员数据。
2. 在构造函数和 Set 函数中增加对传入字符串指针为 NULL 的处理,防止 strcpy 函数出现错误。
3. 在构造函数和 Set 函数中,使用 strncpy 函数限制字符串的拷贝长度,并添加字符串结尾的标识符。
阅读全文