猿问

如下程序,实在是看不明白了,请高人指点呐!

程序要求输出学生、老师、研究生的档案
//档案管理.cpp
#include<iostream.h>
#include<string.h>
class Person
{
char *name;
char sex;
int age;
public:
Person(char *na,char sx,int ag)
{
age=ag;
sex=sx;
name=new char[strlen(na)+1];
strcpy(name,na);
}
void print()const
{
cout<<" "<<name<<":";
cout<<age<<":";
cout<<sex<<endl;
}
~Person()
{
delete[]name;
}
};
class Student:public Person
{
int number;
char department[50];
public:
Student(char*na,char sx,int ag,int num,char*dep)

number=num;
strcpy(department,dep);
}
void print()const
{
Person::print();
cout<<" number:"<<number<<endl;
cout<<" department:"<<department<<endl;
}
};
class Teacher:public Person
{
char post[20],course[30];
public:
Teacher(char*na,char sx,int ag,char*po,char*co):person(na,sx,ag)
{
strcpy(post,po);
strcpy(course,co);
}
void print()const
{
Person::print();
cout<<" post:"<<post<<endl; cout<<" course:"<<course<<endl;
}
};
class Graduatestudent:public Student
{
char advisor[30];
public:
Graduatestudent(char*na,char sx,int ag,int num,char*dep,char*ad):student(na,sx,ag,num,dep)
{
strcpy(advisor,ad);
}
void print()const
{
Student::print();
cout<<" advisor:"<<advisor<<endl;
}
};
void main()
{
Person per1("zhang",'F',23),per2("chen",'M',37);
Student stu1("li",'M',22,1001,"comp"),stu2("cui",'F',21,1002,"math");
Teacher teach1("meng",'M',46,"professor","english");
Graduatestudent grastu("zhou",'M',25,1011,"comp","liu");
cout<<"===per1.print()==>name,age,sex"<<endl;
per1.print();
cout<<"===per2.print()==>name,age,sex"<<endl;
per2.print();
cout<<"===stu1.print()==>name,age,sex,number,department,advisor"<<endl;
grastu.Graduatestudent::print();
}
这个程序运行时总是说Student(char*na,char sx,int ag,int num,char*dep)这一行error C2512: 'Person' : no appropriate default constructor available。

MYYA
浏览 137回答 2
2回答

慕容708150

问题分析:因为派生类在调用自己的构造函数之前需要先调用父类的构造函数,如果你的派生类构造函数初始化列表中没有显式的调用父类的构造函数,他就会自动的调用父类的默认构造函数(也就是不带参数的构造函数),例如类Student在调用自己的构造函数“Student(char*na,char sx,int ag,int num,char*dep)”时需要调用父类的默认构造函数,而其父类Person的默认构造函数你没有定义,所以会出现上述错误。解决方法:给Person类定义默认构造函数,即使什么也不做也要定义一个空函数

HUX布斯

错误主要是因为你的继承类Student中没有为父类定义构造函数,你应该会的,就象Graduatestudent继承类的构造函数一样就行了还有就是大小写问题了你的两次继承类中定义的构造函数都出现了这个问题,要知道大小写可是不同滴呀.1.Teacher(char*na,char sx,int ag,char*po,char*co):Person(na,sx,ag) //Person要大写才是你定义的类嘛{&nbsp;strcpy(post,po);&nbsp;strcpy(course,co);&nbsp;}&nbsp;2.Graduatestudent(char*na,char sx,int ag,int num,char*dep,char*ad):student(na,sx,ag,num,dep)//Studnet要大写嘛&nbsp;{&nbsp;strcpy(advisor,ad);&nbsp;}
随时随地看视频慕课网APP
我要回答