c++ 类与对象

来源:互联网 发布:大数据运维工程师要求 编辑:程序博客网 时间:2024/06/09 15:51

设计一个书类,能够保存书名,定价,所有书的本书和总价。

按书本上代码编写

#include<iostream>#include<cstring>using namespace std;class Book{public :    Book(char *,double);    ~Book();    double getPrice(){return price;}    char * getName(){return bkName;}    static int getNumber(){return number;}    static double getTotalPrice (){return totalPrice;}    void display();private:    char bkName[20];    double price;    static int number;    static double totalPrice;};Book::Book(char *name,double Price){    strcpy(bkName,name);    price=Price;    number++;    totalPrice +=price;}Book::~Book(){    number--;    totalPrice-=price;}void Book::display(){    cout<<"book name :"<<bkName<<"price :"    <<price<<endl;    cout<<"number:"    <<number<<"  "<<"totalprice:"<<totalPrice<<endl;    cout<<"call static function "<<getNumber()<<endl;}int Book::number=0;double Book::totalPrice =0;int main(){    Book b1("C++ 程序设计",32.5);    Book b2("数据库系统原理",23);    cout<<b1.getName()<<"\t"<<b1.getPrice()<<endl;    cout<<b2.getName()<<"\t"<<b2.getPrice()<<endl;    cout<<"总共 : "<<b1.getNumber()<<"\t本书"<<"\t总价:  "<<b1.getTotalPrice()<<"\t元"<<endl;    {        Book b3("数据库系统原理",23);        cout<<"总共 : "<<b1.getNumber()<<"\t本书"<<"\t总价:  "<<b1.getTotalPrice()<<"\t元"<<endl;    }    cout<<"总共 : "<<b1.getNumber()<<"\t本书"<<"\t总价:  "<<b1.getTotalPrice()<<"\t元"<<endl;    b2.display();}
基本上将类基础的部分都用到了,构造函数,析构函数,拷贝,静态成员。



0 0
原创粉丝点击