c++:虚函数、抽象类

//虚函数:函数头部加virtual。可以实现运行时的多态性,通过指向派生类的基类指针,访问派生类中同名覆盖成员函数
//通过虚函数实现了动态的绑定
#include<iostream>
using namespace std;
class Country {
public:
	virtual void name() {
		cout << "this is a country" << endl;
	}
};
class China :public Country{
public:
	virtual void name() { //派生类中重新定义基类的虚函数仍为虚函数,可以省略关键字virtual。
		cout << "this is China" << endl;
	}
};
class Japan:public Country {
public:
	virtual void name() {  //派生类中重新定义基类的虚函数仍为虚函数,可以省略关键字virtual。
		cout << "this is Japan" << endl;
	}
};
int main() {
	Country country,*p;
	China cn;
	Japan jp;
	country = cn;
	country.name(); //this is a country,对象名调用,执行的仍然是基类对象的函数

	//调用虚函数要用引用或指针调用,而不能以对象名调用
	p = &jp;
	p->name();   //this is Japan。指针调用

	Country& p1 = cn;
	p1.name();   //this is China。引用调用

	return 0;
}
/*
纯虚函数: virtual 返回类型 函数名(参数表)= 0
抽象类:至少包含一个纯虚函数。将不用来声明对象(实例化)的类称为抽象类。只供继承
抽象类不能声明对象,但是可以申明指针或引用,只作为基类被继承 
*/
#include<iostream>
#include<cmath>
using namespace std;
#define PI 3.1415
class Shape {  //抽象类的定义
public:
	virtual double area() = 0; //纯虚函数
	virtual double cir() = 0;
};

class Rectangle :public Shape { //矩形类
	int x, y;          //默认为private
	int width, hight;
public:
	Rectangle(int x, int y, int w, int h) { //构造函数
		//this指针指向所声明的对象的首地址
		this->x = x; //x,y为中心点坐标
		this->y = y;
		width = w;  //通过构造函数,改变私有变量width和hight的值
		hight = h;
	}

	virtual double area() {
		return width * hight; //类成员函数直接调用改变后的私有变量width和hight的值
	}

	virtual double cir() {
		return 2.0* (width + hight);
	}

	void printf() {
		cout << "中心点坐标为:(" << x << "," << y <<")"<< endl;
	}
};

class Circle :public Shape {
	int x, y;
	int r;
public:
	Circle(int x, int y, int r) {
		this->x = x;
		this->y = y;
		this->r = r;
	}
	double area() {   //省略了virtual的虚函数
		return PI * r* r;
	}
	double cir() {    //省略了virtual的虚函数
		return 2 * PI* r;
	}
	void printf() {
		cout << "中心点坐标为:(" << x << "," << y << ")" << endl;
	}
};
//下面是主函数部分
int main() {
	Rectangle r1(10, 10, 5, 10);
	Circle c1(3, 1, 3);
	Shape* p1 = &r1; //声明抽象类指针
	Shape& p2 = c1;  //声明抽象类引用,引用对象为p2,类型为Shape&
	cout << "长方形面积为:" << p1->area() << endl;
	cout << "长方形周长为:" << p1->cir() << endl;
	r1.printf();    //使用p1->printf();会报错,因为p1为Shape类的指针,而Shape类中没有printf函数
	cout << "圆的面积为:" << c1.area() << endl;
	cout << "圆的周长为:" << c1.cir() << endl;
	c1.printf();
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值