我有一个虚拟课程的人,从中派生到2个班级的学生和老师:
有些人可以告诉我如何将p [counter]初始化为老师或学生吗?这是虚函数
class person
{
public:
string name;
int age;
virtual void print()=0;
};
第一个派生班主任
class teacher : public person
{
public:
int salary;
teacher();
teacher(int x,string y,int z);
void print();
};
第二个派生班学生
class student : public person
{
public:
char grade;
double fees;
student();
student(string a,int b,char c,double d);
void print();
};
int main()
{
cout<<"Insert 's' for student and 't' for teacher"<<endl;
string S;
cin>>S;
person *p;
here you either enter s for student or t for teacher, and also we create a dynamic array for p as type person
for(int counter=0;counter<4;counter++)
{
if (S=="s" || S=="S")
{
string name;
int age;
char grade;
int fees;
cout<<"Input name,age,grade,fees"<<endl;
cin>>name;
cin>>age;
cin>>grade;
cin>>fees;
p[counter]=student(name,age,grade,fees);
}
上面是p [计数器无法初始化为学生的地方,它给了我一个错误,然后说p不是在运行时错误初始化 我尝试添加新的,但它给了我一个编译错误... 否则如果(S ==“t”|| S ==“T”) {
string name2;
int age2;
int salary;
cout<<"Input age,name,salary"<<endl;
cin>>name2;
cin>>age2;
cin>>salary;
p[counter]=teacher(age2,name2,salary);
}
这里我们对老师有同样的看法 其他 { COUT&LT;&LT; “错误” &LT;
cin>>S;
}
cout<<endl<<endl<<endl;
delete [] p;
return 0;
}
这里是函数实现
teacher::teacher()
{
name="None";
age=0;
salary=0;
}
teacher::teacher(int x,string y,int z)
{
name=y;
age=x;
salary=z;
}
void teacher::print()
{
cout<<"Dr."<<name<<endl
<<"age:"<<age<<endl
<<"slary:"<<salary<<"$"<<endl;
}
student::student()
{
name="None";
age=0;
grade='F';
fees=0;
}
student::student(string a,int b,char c,double d)
{
name=a;
age=b;
grade=c;
fees=d;
}
void student::print()
{
cout<<"Student: "<<name<<endl
<<"Age: "<<age<<endl
<<"Grade: "<<grade<<endl
<<"Fees: "<<fees<<" $"<<endl;
}
答案 0 :(得分:1)
有一些错误:
P
是一个指针,你试图将它用作一个指针数组。
因为counter
似乎循环了4次。因此,您可以将p
定义为person *p[4];
这将创建基类人员的指针数组。
然后在分配p[counter]=student(name,age,grade,fees);
或p[counter]=teacher(age2,name2,salary);
时,您必须使用new
运算符。那就是
p[counter]=new student(name,age,grade,fees);
和
p[counter]=new teacher(age2,name2,salary);