#C++ 1:派生类构造函数的类外定义
最近上课在看课本的时候发现派生类都是在类内定义的,自己写代码想要按普通类的方式类外定义的时候出现了报错,如下:
class CStudent:public CPerson{
private:
string course;
float grade;
public:
CStudent(string nam,string nu,string cou,float gra):CPerson(nam,nu);
void StuOut();
};
CStudent::CStudent(string nam,string nu,string cou,float gra):CPerson(nam,nu){
course=cou;
grade=gra;
后来发现对基类构造函数的引用不能同时出现在类内声明和类外定义中,于是可以做两种修改:
class CStudent:public CPerson{
private:
string course;
float grade;
public:
CStudent(string nam,string nu,string cou,float gra):CPerson(nam,nu){course=cou;grade=gra;}
void StuOut();
};
- 方法2:在类内只声明,不引用基类的构造函数;在类外定义+引用基类构造函数
class CTeacher:public CPerson{
private:
string title;
int papern;
public:
CTeacher(string nam,string nu,string ti,int pn);
void TeaOut();
};
CTeacher::CTeacher(string nam,string nu,string ti,int pn):CPerson(nam,nu){
title=ti;
papern=pn;
}
|