溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

如何使用c++中的純虛函數和抽象類

發(fā)布時間:2021-10-14 09:16:54 來源:億速云 閱讀:139 作者:柒染 欄目:編程語言

本篇文章給大家分享的是有關如何使用c++中的純虛函數和抽象類,小編覺得挺實用的,因此分享給大家學習,希望大家閱讀完這篇文章后可以有所收獲,話不多說,跟著小編一起來看看吧。

/*純虛函數與抽象類-----枯等街寒又何妨2014/01/05*/
#include<iostream>
#include<cmath>
using namespace std;
const double pi=3.14159;
class Shape
{
 public:
 virtual void show(void)=0;
 virtual double area(void)=0;
};

class triangle:public Shape
{
 public:
  triangle(double=0,double=0,double=0);
  void show(void);
  double area(void);
  private:
  double a,b,c;
};

class rectangle :public Shape
{
 public:
  rectangle(double=0,double=0);
  void show(void );
  double area(void );
 private:
 double width,length;
};

class circle :public Shape
{
 public:
  circle(double =0);
  void show(void);
  double area(void);
 private:
  double r;
};

triangle::triangle(double a1,double b1,double c1)
{
 a=a1;b=b1;c=c1;
}

void triangle::show(void)
{
 cout<<"a="<<a<<"\tb="<<b<<"\tc="<<c<<endl;
}

double triangle::area(void)
{
 double s=(a+b+c)/2;
 return sqrt(s*(s-a)*(s-b)*(s-c));
}

rectangle::rectangle(double a,double b)
{
 length=a;width=b;
}

void rectangle::show(void )
{
 cout<<"wigth="<<width<<"\tlength="<<length<<endl;
}

double rectangle::area(void)
{
 return (width*length);
}

circle::circle(double a)
{
 r=a;
}

void circle::show()
{
 cout<<"r="<<r<<endl;
}

double circle::area(void )
{
 return pi*r*r;
}

int main()
{
 circle r(10);
 triangle s(3,4,5);
 rectangle l(2,5);
 r.show();
 s.show();
 l.show();
 cout<<r.area()<<endl;
 cout<<s.area()<<endl;
 cout<<l.area()<<endl;
 system("pause"); 
 return 1;
}

以上就是如何使用c++中的純虛函數和抽象類,小編相信有部分知識點可能是我們日常工作會見到或用到的。希望你能通過這篇文章學到更多知識。更多詳情敬請關注億速云行業(yè)資訊頻道。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

c++
AI