注册 登录
编程论坛 C++教室

继承与派生

亦尘 发布于 2011-11-30 13:17, 828 次点击
求教高手啊,继承不是不能继承基类的构造函数吗???可是我的程序竟然继承啦???求解啊
#include<iostream.h>
#include<string.h>

//基类person
class person
{
protected:
    char name[10];
    char sex[4];
    int age;
public:
    person(){}
    ~person(){}
    void show(){}
};





//派生student类
class student:virtual public person
{
protected:
    char speciality[10];  //学生的专业
    int num;             //学生的学号
public:
    student();
    ~student();
    void show();
};

//student类构造函数的实现
student::student()
{
    cout<<"请输入学生的信息:"<<endl;
    cout<<"学号:";
    cin>>num;
    cout<<"姓名:";
    cin>>name;
    cout<<"性别:";
    cin>>sex;
    cout<<"年龄:";
    cin>>age;
    cout<<"专业:";
    cin>>speciality;
}

//析构函数
student::~student()
{
}

//显示函数的实现
void student::show()
{
    cout<<"学生的信息如下:"<<endl;
    cout<<"学号"<<"   "<<"姓名"<<"   "<<"性别"<<"   "<<"年龄"<<"   "<<"专业"<<endl;
    cout<<num<<"   "<<name<<"   "<<sex<<"   "<<age<<"   "<<speciality<<endl;
}








//teacher类
class teacher:virtual public person
{
protected :
     char department[20];
public:
    teacher();
    ~teacher();
    void show();
};

//teacher类构造函数的实现
teacher::teacher()
{
    cout<<"请输入老师的信息:"<<endl;
    cout<<"姓名:";
    cin>>name;
    cout<<"性别:";
    cin>>sex;
    cout<<"年龄:";
    cin>>age;
    cout<<"院系:";
    cin>>department;
}


//析构函数的实现
teacher::~teacher()
{
}

//显示函数的实现
void teacher::show()
{
    cout<<"老师的信息如下:"<<endl;
    cout<<"姓名"<<"   "<<"性别"<<"   "<<"年龄"<<"   "<<"院系"<<endl;
    cout<<name<<"   "<<sex<<"   "<<age<<"   "<<department<<endl;
}







//派生类stuteacher
class  stuteacher: public student, public teacher
{
public:
    stuteacher();
    ~stuteacher();
    void show();
};

//stuteacher类构造函数的实现
stuteacher::stuteacher()
{
    cout<<"请输入在读老师的信息:"<<endl;
    cout<<"姓名:";
    cin>>name;
    cout<<"性别:";
    cin>>sex;
    cout<<"年龄:";
    cin>>age;
    cout<<"院系:";
    cin>>department;
    cout<<"专业";
    cin>>speciality;
}


//析构函数的实现
stuteacher::~stuteacher()
{
}


//stuteacher类显示函数的实现
void stuteacher::show()
{
    cout<<"老师的信息如下:"<<endl;
    cout<<"姓名"<<"   "<<"性别"<<"   "<<"年龄"<<"   "<<"院系"<<"   "<<"专业"<<endl;
    cout<<name<<"   "<<sex<<"   "<<age<<"   "<<department<<"   "<<speciality<<endl;
}



void main()
{
    student objs;
    objs.show();
    teacher objt;
    objt.show();
    stuteacher objst;
    objst.show();
}
6 回复
#2
我菜1192011-11-30 20:18
我不知道你要表达个什么意思
#3
亦尘2011-12-01 22:14
你用vc6.0运行一下看看结果啊,我最后只想输如stuteacher那个对象的成员啊,可是却每一个都要输入一遍
#4
鑫乐源2011-12-01 22:38
再去看看c++类吧,构造函数先调用基类构造,然后依次调用派生类构造函数。
#5
我是菜鸟C2011-12-02 09:11
继承是不能继承基类的构造函数。

你这样调试运行的时候再stuteacher中会出现基类的构造函数是因为:
在stuteacher的构造过程中会调用基类的构造函数!这是调用不是继承!

建议不要这样定义构造函数,你需要赋值的话建议再定义一个函数,GetData()来获取对象信息,这个是可以继承的。

[ 本帖最后由 我是菜鸟C 于 2011-12-2 09:13 编辑 ]
#6
jj74125302011-12-06 00:55
4L正解,子类在进行构造结构之前会先调用基类的构造函数,你可以理解为其子类第一个成员变量是父类的对象,只不过其被优化隐藏了
这样在进行构造函数之前会先按照声明顺序分配空间就会调用基类构造函数
#7
亦尘2011-12-09 20:41
谢谢给位啦
1