C 虛函式機制實現多型性

2021-09-11 21:33:25 字數 1942 閱讀 5103

// 2019.cpp : 定義控制台應用程式的入口點。

//#include "stdafx.h"

#include// 定義抽象基類(包含有純虛函式的類就成為抽象類或者抽象基類)

class shape

virtual float volume() const

// 定義該函式為純虛函式

virtual void shapename() const = 0;

// 定義虛析構函式

virtual ~shape() };

// public繼承

class point :public shape

void setpoint(float, float);

float getx() const

float gety() const

virtual void shapename() const

friend std::ostream & operator << (std::ostream &, const point &);

protected:

float x, y;

};point::point(float a, float b)

void point::setpoint(float a, float b)

std::ostream & operator << (std::ostream&output, const point&p)

class circle :public point

void setradius(float);

float getradius() const;

virtual float area() const;

virtual void shapename() const

friend std::ostream & operator << (std::ostream &, circle &);

protected:

float radius;

};circle::circle(float x, float y, float r) :point(x, y), radius(r) {}

void circle::setradius(float r)

float circle::getradius() const

float circle::area() const

std::ostream & operator << (std::ostream&output, circle&c)

class cylinder :public circle

void sethight(float);

float getheight() const;

virtual float area() const;

virtual float volume() const;

virtual void shapename() const

friend std::ostream & operator << (std::ostream&, cylinder&);

protected:

float height;

};cylinder::cylinder(float x, float y, float r, float h) :circle(x, y, r), height(h) {}

void cylinder::sethight(float h)

float cylinder::getheight() const

float cylinder::area() const

float cylinder::volume() const

std::ostream & operator << (std::ostream&output, cylinder&c)

int main()

虛函式,實現多型性的重要機制

按慣例以例項做分析。include using namespace std enum note class instrument int main 以上 出自 thinking in c 一書,所以我只是將對書內內容做總結跟位元組的理解描述出來,如有不解之處請參考書本。我們知道,函式tune 通過引...

c 多型性 虛函式

c 中多型性是指通過用virtual關鍵字來繫結同名同引數的函式,實現在編譯中進行後繫結,即在編譯過程中不繫結類,在執行時與具體的物件進行繫結,這樣就可以動態地與實際聯絡 比如乙個類 animal 有乙個虛函式breath 魚類 fish 也有函式breath 狗類 dog 函式breath 具體呼...

c 多型性 虛函式

虛函式與純虛函式的區別 1 擁有虛函式的類可以宣告物件,但擁有純虛函式的類不可以宣告物件 只能宣告乙個指標,並且不能給其分配記憶體 並且將這個類稱為抽象類 特點 1 虛函式是動態繫結的基礎。2 是非靜態的成員函式。在類的宣告中,在函式原型之前寫virtual。不能宣告為靜態函式 3 virtual ...