问题描述
- 类构造函数的问题(继承)
-
#include <iostream> using namespace std; class People { protected: char name[20],xb[10],id[21]; int num,all,week; public:People() { } public:People(char na[20],int nu,char x[10],char idc[21],int al,int wk) { strcpy_s(name,na); num=nu; strcpy_s(xb,x); strcpy_s(id,idc); all=al; week=wk; } virtual void show() { cout<<name<<'t'<<num<<'t'<<xb<<endl<<id<<'t'<<all<<'t'<<week<<endl; } }; //学生 class Student: virtual public People { public: Student(char na[20],int nu,char x[10],char idc[21],int al,int wk){}; }; //教师 class Teacher:virtual public People { protected: int teach; public: Teacher(char na[20],int nu,char x[10],char idc[21],int al,int wk,int tean); void show() { cout<<name<<'t'<<num<<'t'<<xb<<endl<<id<<'t'<<all<<'t'<<week<<'t'<<teach<<endl; } }; Teacher::Teacher(char na[20],int nu,char x[10],char idc[21],int al,int wk,int tean):People(na,nu,x,idc,al,wk) { teach=tean; }; class Graduate:virtual public Student { protected: char project[30]; public: Graduate(char na[20],int nu,char x[10],char idc[21],int al,int wk,char pro[30]):Student(na,nu,x,idc,al,wk) { strcpy_s(project,pro); } void show() { cout<<name<<'t'<<num<<'t'<<xb<<endl<<id<<'t'<<all<<'t'<<week<<'t'<<project<<endl; } }; class Ta:public Graduate ,public Teacher { protected: char project[30]; int teachT; public: Ta(char na[20],int nu,char x[10],char idc[21],int al,int wk,char proT[30],int teaT):Student(na,nu,x,idc,al,wk) { strcpy_s(project,proT); teachT=teaT; } void show() { cout<<name<<'t'<<num<<'t'<<xb<<endl<<id<<'t'<<all<<'t'<<week<<'t'<<project<<'t'<<teach<<endl; } }; int main() { People pe("kkjl",5,"xkjkj","idcxxxx",5,6); pe.show(); Teacher tr("kkjl",5,"xkjkj","idcxxxx",5,6,7); tr.show(); Graduate gd("kkjl",5,"xkjkj","idcxxxx",5,6,"proxxxxx"); gd.show(); return 0; }
我想问TA类的构造函数哪里错了呢?
它说“Graduate”: 没有合适的默认构造函数可用..“Teacher”: 没有合适的默认构造函数可用
还有..gd.show(); 输出的数据为什么会溢出呢?..
T^T求高手帮忙,,我研究半天了,,还是不懂..
谢谢了T^T
解决方案
在每个子类的构造函数增加一句Base()。
时间: 2024-10-26 15:45:15