虚函数的使用(三层继承)
#include <iostream>
#include <string>
#pragma warning(disable:4996)
using namespace std;
class person
{
protected:
char *name;
int age;
char sex;
public:
person(char *, int, char);
virtual void show();
virtual ~person()
{
delete []name;
cout << "调用基类person的析构函数 " << endl;
}
};
person::person(char *name, int age, char sex) :age(age), sex(sex)
{
this->name = new char[strlen(name) + 1];
strcpy(this->name, name);
cout << "调用基类person的构造函数 " << endl;
}
void person::show()
{
cout << "调用基类person的show()函数 " << endl;
}
class student:public person
{
protected:
int ID;
char *major;
public:
student(char *name, int age, char sex, int ID, char *major);
void show();
~student()
{
delete []major;
cout << "调用一级派生类student的析构函数 " << endl;
}
};
student::student(char *name, int age, char sex, int ID, char *major) :person(name, age, sex), ID(ID)
{
this->major = new char[strlen(major) + 1];
strcpy(this->major, major);
cout << "调用一级派生类student的构造函数 " << endl;
}
void student::show()
{
cout << "调用派生类student的show()函数 " << endl;
}
class graduate:public student
{
private:
char *mentor;
public:
graduate(char *name, int age, char sex, int ID, char *major, char *mentor);
void show();
~graduate()
{
delete[]mentor;
cout << "调用二级派生类student的析构函数 " << endl;
}
};
graduate::graduate(char *name, int age, char sex, int ID, char *major, char *mentor) :student(name, age, sex, ID, major)
{
this->mentor = new char[strlen(mentor) + 1];
strcpy(this->mentor, mentor);
cout << "调用二级派生类student的构造函数 " << endl;
}
void graduate::show()
{
cout << "调用派生类graduate的show()函数 " << endl;
}
void main()
{
graduate a1("xiaozhang", 20, 'N', 2014210579, "通信", "乔建");
person *b;
b = &a1;
b->show();
person &c = a1;
c.show();
}
执行结果
#pragma warning(disable:4996)
VS2013不支持strcpy 语句,加上这句话,使用strcpy对字符串赋值
person::person(char *name, int age, char sex) :age(age), sex(sex)
{
this->name = new char[strlen(name) + 1];
strcpy(this->name, name);
cout << "调用基类person的构造函数 " << endl;
}
this 指针的使用,派生类构造函数 的使用
虚函数要点语法:
1.如果在函数声明的时候已经用virtual 指明了虚函数,在类外定义的时候就不需要再次说明了,当然也可以直接声明加定义在类内一并完成
2.在基类中声明了虚函数,派生类中的同名函数无论是否声明都会自动成为虚函数(为了方便读,还是都注明虚函数)
3.要想得到有效的虚函数,派生类的继承方式一定是public继承
4.在多级继承中,可以在第二级再声明虚函数,那么第三层的虚函数可以动态联编,第一层的同名函数和2、3层同名函数的关系就还是普通同名函数之间的关系,不会动态联编
5.虚函数之间的返回类型,函数名,形参个数必须完全相同
6.静态成员函数和构造函数不能成为虚函数如果第二层没有虚函数(未定义同名函数),在第三层定义了同名函数,那么第三层的同名函数仍然是虚函数