1、什麼是多態。
從屬於不同的類對象 , 調用相同的函數(同名函數),最終會具體調用不同的代碼,實現不同的功能, 這就是多態
#include <iostream>
using namespace std;
class point
{
private:
int xres;
int yres;
public:
//點類的建構函式
point(int x, int y)
{
//cout<<"point constructor"<<endl;
xres = x;
yres = y;
}
virtual void display() //定義為虛函數
{
cout<<"xres: "<<xres<<" "<<"yres: "<<yres<<endl;
}
};
class rectangle : public point
{
private:
int xres;
int yres;
int width;
int height;
public:
rectangle(int x, int y, int w, int h):point(x,y)
{
xres = x;
yres = y;
width = w;
height = h;
}
void display()
{
cout<<"rec_xres: "<<xres<<" "<<"rec_yres: "<<yres<<endl;
cout<<"width: "<<width<<" "<<"height: "<<height<<endl;
}
};
class circle : public point
{
private:
int xres;
int yres;
int radus;
public:
//基類中有建構函式,編譯過程中分配了空間,需要對其初始化。若不要初始化,就不要出現建構函式
circle(int x, int y, int r):point(x,y) //如果去掉point(x,y)會報錯,可以刪掉基類的建構函式或者基類成員。
{
xres = x;
yres = y;
radus = r;
}
void display()
{
cout<<"cir_xres: "<<xres<<" "<<"cir_yres: "<<yres<<endl;
cout<<"cir_r: "<<radus<<endl;
}
};
int main()
{
/*測試1
point p(10, 20);
point *ptr = &p;
ptr->display(); //調用的是基類的成員函數
rectangle rec(100, 200, 300, 400);
ptr = &rec;
ptr->display(); //調用的是基類的成員函數
*/
//測試點
rectangle rec(100, 200, 300, 400);
circle cir(10, 20, 80);
point *ptr;
//調用矩形列印
ptr = &rec;
ptr->display(); //在基類中定義為虛函數之後,這裡調用的是rectangle衍生類別的成員函數
ptr = ○
ptr->display(); //在基類中定義為虛函數之後,這裡調用的是circle衍生類別的成員函數
return 0;
}
2、純虛函數
1)什麼是純虛函數
在基類中定義虛函數
virtual void dispaly();
基類一定要定義,但是基類不應該:
a、定義資料成員
b、建構函式
c、虛函數有必要存在,但是不能有具體實現內容
所以最終基類,只能用來聲明虛函數存在,並且可以寫成
virtual void dispaly(); //純虛函數
樣本函數:
#if 0
#include<iostream>
#include<stdio.h>
#include<string>
#include<math.h>
using namespace std;
#define pi 3.14
class Shape// 定義圖形
{
public:
virtual string getName() = 0; // 定義第一個純虛函數
virtual float getArea() = 0; // 定義第二個純虛函數
};
class Circle : public Shape
{
public:
Circle(string n, int x, int y, int r)
{
name = n;
xres = x;
yres = y;
radius = r;
}
string getName(void)
{
return name;
}
float getArea(void)
{
return pi*radius*radius;
}
private:
string name;
float xres;
float yres;
float radius;
};
class Rectangle : public Shape
{
public:
Rectangle(string n, float x, float y, float w, float h)
{
name = n;
xres = x;
yres = y;
width= w;