虚函数的使用

虚函数的使用(三层继承)

#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.静态成员函数和构造函数不能成为虚函数如果第二层没有虚函数(未定义同名函数),在第三层定义了同名函数,那么第三层的同名函数仍然是虚函数




转载于:https://my.oschina.net/CRAZYZONE/blog/634141

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值