我正在为我的类(class)做我的第一个C++程序。我真的是这个程序的新手,所以我有很多东西要学习。在我的程序中,我想用Undergrad / grad / gradassist派生的类创建一个Student类。名称和SSN字段必须位于char数组中(我知道字符串更有意义,但老师要求使用char数组)。该程序除不能在我的char数组中打印任何内容外,几乎都能正常运行。请帮忙!
#include <iostream>;
using namespace std;
class Student {
protected:
char name[21];
char ssn[10];
float gpa;
int credits;
public:
Student::Student() {};
Student(const char n[], const char ss[], float& gp, int& cred) {
name[21] = n[21];
ssn[10] = ss[10];
gpa = gp;
credits = cred;
}
virtual void print() {
cout << "Name: " << name << endl;
cout << "SSN: " << ssn << endl;
cout << "GPA: " << gpa << endl;
cout << "Credits: " << credits << endl;
}
virtual float tuition() const = 0;
};
class undergrad : public Student {
protected:
float undergrad_rate;
char* year;
public:
undergrad::undergrad() {}
undergrad(float ugr, char* yr, const char n[], const char ss[], float&
gp, int& cred) :
Student(n, ss, gp, cred), undergrad_rate(ugr), year(yr){}
void set_year(char* yr) {
year = yr;
}
char* getYear() {
return year;
}
float getRate() {
return undergrad_rate;
}
void print() {
Student::print();
cout << "Undergrad rate: " << undergrad_rate << endl;
cout << "year: " << year << endl;
}
float tuition() {
//cout << "The tuition is $35000" << endl;
return 35000;
}
};
class grad : public Student {
protected:
float grad_rate;
char* thesis;
public:
};
int main(){
char* jr = "Junior";
char* sr1 = "Senior";
char* fr = "Freshman";
char* sr = "Sophmore";
undergrad g(380, jr, "M", "000111222", 4.0, 12);
g.print();
system("pause");
return 0;
}
最佳答案
问题就在这里,这是初始化成员名称和ssn的方式:
Student(const char n[], const char ss[], float& gp, int& cred) {
name[21] = n[21];
ssn[10] = ss[10];
这里有不止一件事
为了按照您想要的方式初始化这些成员变量,请执行以下操作:
Student(const char n[], const char ss[], float& gp, int& cred) {
strcpy_s(name, sizeof(name), n);
strcpy_s(ssn, sizeof(ssn), ss);
这会将包含输入字符串的所有字符复制到您的成员变量中,您将获得所需的输出。
关于c++ - 我的C++程序中的char数组不会打印任何内容,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49411720/