CStudent::CStudent(char *pName, int n, int C, int P, int History) { strcpy(name, pName); num = n; Chinese =C; Physical = P; this->History = History; }cout << "用带参数的构造函数创建对象:" << endl; CStudent s2("顾斌", 221404205, 120, 98, 70); cout << sizeof(s2) << endl; cout << s2.getName()<< " " << s2.getNum() << " " << s2.getChinese() << " " << s2.getHistory() << " " << s2.getPhysical() << endl;这段代码哪里错了
时间: 2023-08-20 12:22:04 浏览: 67
这段代码没有明显的语法错误,但是需要注意以下几点:
1. 在构造函数的参数列表中,建议使用 const char* 类型来表示字符串,而不是 char* 类型,以避免不必要的内存问题。
2. 在输出对象属性值时,应该使用成员函数而不是直接访问对象属性,以保证封装性和安全性。
3. 在输出对象属性值时,应该按照属性的顺序输出,而不是随意输出,以方便阅读。
以下是修改后的代码:
```
class CStudent {
public:
CStudent(const char* pName, int n, int C, int P, int History) {
strcpy(name, pName);
num = n;
Chinese = C;
Physical = P;
this->History = History;
}
const char* getName() const {
return name;
}
int getNum() const {
return num;
}
int getChinese() const {
return Chinese;
}
int getPhysical() const {
return Physical;
}
int getHistory() const {
return History;
}
private:
char name[20];
int num;
int Chinese;
int Physical;
int History;
};
int main() {
cout << "用带参数的构造函数创建对象:" << endl;
CStudent s2("顾斌", 221404205, 120, 98, 70);
cout << "姓名:" << s2.getName() << endl
<< "学号:" << s2.getNum() << endl
<< "语文:" << s2.getChinese() << endl
<< "数学:" << s2.getPhysical() << endl
<< "历史:" << s2.getHistory() << endl;
cout << "对象大小:" << sizeof(s2) << endl;
return 0;
}
```
阅读全文