[C++ Primer Plus] 第10章、對象和類(一)程序清單——辨析三個const

程序清單10.1+10.2+10.3

頭文件stock.h
#ifndef STOCK00_H_    //先測試x是否被宏定義過
#define STOCK00_H_    //若是沒有宏定義,就宏定義x並編譯下面的語句

#include <string>
class Stock        //類聲明
{
private:
    std::string company;
    long shares;
    double share_val;
    double total_val;
    void set_tot()    {    total_val=shares*share_val;    }
public:
    void acquire(const std::string &co,long n,double pr);
    void buy(long num,double price);
    void sell(long num,double price);
    void update(double price);
    void show();
};    //千萬別忘了分號

#endif    //若是已經定義了則編譯#endif後面的語句

stock.cppios

#include<iostream>
#include "stock.h"

void Stock::acquire(const std::string &co,long n,double pr){
    company=co;
    if(n<0){
        std::cout<<company<<std::endl;
        shares=0;
    }else
        shares=n;
    share_val=pr;
    set_tot();
} 
    
void Stock::buy(long num,double price){
    if(num<0)
        std::cout<<"Error!\n";
    else{
        shares+=num;
        share_val=price;
        set_tot();
    }
} 

void Stock::sell(long num,double price){
    using std::cout;
    if(num<0)
        cout<<"Error!\n";
    else if(num>shares)
        cout<<"You can not sell more than you have!\n";
    else{
        shares-=num;
        share_val=price;
        set_tot();
    }
}

void Stock::update(double price){
    share_val=price;
    set_tot();
}

void Stock::show(){
    std::cout<<"Company: "<<company<<", Shares:"<<shares<<"\nShare Price: $"<<share_val<<", Total Worth: $"<<total_val<<'\n';
}

main.cpp函數

//用於測試Stock類的設計
#include<iostream>
#include "stock.h"

void main(){
    Stock cat;
    cat.acquire("NanoSmart",20,12.50);
    cat.show();
    cat.buy(15,18.125);
    cat.show();
    cat.sell(400,20.0);
    cat.show();
    cat.buy(300000,40.125);
    cat.show();
    cat.sell(300000,0.125);
    cat.show();
    system("pause");
}

修改stock.cpp文件中的show方法,使其數字格式統一測試

void Stock::show(){
    using std::cout;
    using std::ios_base;
    ios_base::fmtflags orig=cout.setf(ios_base::fixed,ios_base::floatfield);//設置cout對象的一個標記,命令cout使用定點表示法
    std::streamsize prec=cout.precision(3);//cout使用定點表示法時,顯示三位小數

    cout<<"Company: "<<company<<", Shares:"<<shares<<"\nShare Price: $"<<share_val<<", Total Worth: $"<<total_val<<'\n';
    cout.setf(orig,ios_base::floatfield);
    cout.precision(prec);
}

 

小結

 

構造函數和析構函數

程序清單10.4+10.5+10.6

頭文件ui

#ifndef STOCK10_H_    //先測試x是否被宏定義過
#define STOCK10_H_    //若是沒有宏定義,就宏定義x並編譯下面的語句
#include <string>

class Stock        //類聲明
{
private:
    std::string company;
    long shares;
    double share_val;
    double total_val;
    void set_tot()    {    total_val=shares*share_val;    }
public:
    Stock();    //默認構造函數
    Stock(const std::string &co,long n=0,double pr=0.0);
    ~Stock();    //析構函數
    void buy(long num,double price);
    void sell(long num,double price);
    void update(double price);
    void show();
};    //千萬別忘了分號

#endif    //若是已經定義了則編譯#endif後面的語句

函數定義this

#include<iostream>
#include "stock.h"
using namespace std;

//構造函數
Stock::Stock(){
    cout<<"Default constructor called\n";
    company="no name";
    shares=0;
    share_val=0.0;
    total_val=0.0;
}
Stock::Stock(const std::string &co,long n,double pr){
    cout<<"Constructor using "<<co<<" called\n";
    company=co;
    if(n<0){
        cout<<company<<endl;
        shares=0;
    }else
        shares=n;
    share_val=pr;
    set_tot();
} 
//類的析構函數
Stock::~Stock(){
    cout<<"Bye, "<<company<<endl;
}
    
void Stock::buy(long num,double price){
    if(num<0)
        std::cout<<"Error!\n";
    else{
        shares+=num;
        share_val=price;
        set_tot();
    }
} 

void Stock::sell(long num,double price){
    if(num<0)
        cout<<"Error!\n";
    else if(num>shares)
        cout<<"You can not sell more than you have!\n";
    else{
        shares-=num;
        share_val=price;
        set_tot();
    }
}

void Stock::update(double price){
    share_val=price;
    set_tot();
}

void Stock::show(){
    ios_base::fmtflags orig=cout.setf(ios_base::fixed,ios_base::floatfield);//設置cout對象的一個標記,命令cout使用定點表示法
    streamsize prec=cout.precision(3);//cout使用定點表示法時,顯示三位小數
    cout<<"Company: "<<company<<", Shares:"<<shares<<"\nShare Price: $"<<share_val;
    cout.precision(2);//顯示2位小數
    cout<<", Total Worth: $"<<total_val<<endl;
    cout.setf(orig,ios_base::floatfield);
    cout.precision(prec);
}

主函數lua

#include<iostream>
#include "stock.h"

void main(){
    {
        using std::cout;
        cout<<"Using constructors to create new objects!!!\n";
        Stock stock1("NanoSmart",12,20.0);
        stock1.show();
        Stock stock2=Stock ("Boffo Object",2,2.0);
        stock2.show();

        cout<<"Assigning stock1 to stock2!!!\n";
        stock2=stock1;
        cout<<"Listing stock1 and stock2:\n";
        stock1.show();
        stock2.show();

        cout<<"Using a constructor to reset an object!!!\n";
        stock1=Stock("Nifty Foods",10,50.0);
        cout<<"Revised stock1:\n";
        stock1.show();
        cout<<"Done\n";
    }//代碼執行到此處後,調用析構函數。若沒有這對括號,程序將在代碼退出時調用(即咱們沒法觀察到析構函數的調用)
    system("pause");
}

最後兩行輸出是析構函數調用的結果。spa

棧先進後出設計

 

辨析三個const

 如聲明  const int func(const int & a) constcode

第一個表示返回值是個int型的常值
第二個表明const int的引用,a可讀不可改
第三個表明這個函數類中的成員變量,不可修改
對象

const Stock & topval(const Stock &s) const;//返回const Stock類型的引用:參數是引用,返回值也是引用

程序清單10.7+10.8+10.9(this)

#ifndef STOCK    
#define STOCK    
#include <string>

class Stock        //類聲明
{
private:
    std::string company;
    long shares;
    double share_val;
    double total_val;
    void set_tot()    {    total_val=shares*share_val;    }
public:
    Stock();    //默認構造函數
    Stock(const std::string &co,long n=0,double pr=0.0);
    ~Stock();    //析構函數
    void buy(long num,double price);
    void sell(long num,double price);
    void update(double price);
    void show() const;    //const在後面表示不可修改函數內部的值
    const Stock & topval(const Stock &s) const;//返回const Stock類型的引用:參數是引用,返回值也是引用
};    //千萬別忘了分號

#endif    
#include<iostream>
#include "stock.h"
using namespace std;

//構造函數
Stock::Stock(){
    company="no name";
    shares=0;
    share_val=0.0;
    total_val=0.0;
}
Stock::Stock(const std::string &co,long n,double pr){
    company=co;
    if(n<0){
        cout<<company<<endl;
        shares=0;
    }else
        shares=n;
    share_val=pr;
    set_tot();
} 
//類的析構函數
Stock::~Stock(){
}
    
void Stock::buy(long num,double price){
    if(num<0)
        std::cout<<"Error!\n";
    else{
        shares+=num;
        share_val=price;
        set_tot();
    }
} 

void Stock::sell(long num,double price){
    if(num<0)
        cout<<"Error!\n";
    else if(num>shares)
        cout<<"You can not sell more than you have!\n";
    else{
        shares-=num;
        share_val=price;
        set_tot();
    }
}

void Stock::update(double price){
    share_val=price;
    set_tot();
}

void Stock::show() const{
    ios_base::fmtflags orig=cout.setf(ios_base::fixed,ios_base::floatfield);//設置cout對象的一個標記,命令cout使用定點表示法
    streamsize prec=cout.precision(3);//cout使用定點表示法時,顯示三位小數
    cout<<"Company: "<<company<<", Shares:"<<shares<<"\n    Share Price: $"<<share_val;
    cout.precision(2);//顯示2位小數
    cout<<", Total Worth: $"<<total_val<<endl;
    cout.setf(orig,ios_base::floatfield);
    cout.precision(prec);
}

const Stock & Stock::topval(const Stock &s) const{
    if(s.total_val>total_val)
        return s;
    else 
        return *this;
} 
#include<iostream>
#include "stock.h"

const int STKS=4;
void main(){
    Stock stocks[STKS]={
        Stock("Nano",12,20.0),
        Stock("Boffo",200,2.0),
        Stock("Mono",130,3.25),
        Stock("Fleep",60,6.5),
    };
    std::cout<<"Stock holdings:\n";
    int st;
    for (st = 0; st < STKS; st++)
        stocks[st].show();
    const Stock * top=&stocks[0];
    for (st = 1; st < STKS; st++)
        top=&top->topval(stocks[st]);
    std::cout<<"\nMost valuale holding:\n";
    top->show();
    system("pause");
}

程序清單10.10+10.11+10.12(棧)

#ifndef STACK    
#define STACK    

typedef unsigned long Item;

class Stack        //類聲明
{
private:
    enum{MAX=10};
    Item items[MAX];
    int top;
public:
    Stack();    //默認構造函數
    bool isempty() const;
    bool isfull() const;
    bool push(const Item & item);//壓棧
    bool pop(Item & item);//出棧
};    

#endif    
#include "stack.h"

//構造函數
Stack::Stack(){
    top=0;
}

bool Stack::isempty() const{
    return top==0;//top爲0返回true,反之爲false
}
bool Stack::isfull() const{
    return top==MAX;
}
bool Stack::push(const Item &item){
    if(top<MAX){
        items[top++]=item;
        return true;
    }else
        return false;
}
bool Stack::pop(Item &item){
    if(top>0){
        item=items[--top];
        return true;
    }else
        return false;
}
#include<iostream>
#include<cctype>
#include "stack.h"
using namespace std;

void main(){
    Stack st;
    char ch;
    unsigned long po;
    cout<<"Enter A to add a purchase order, P to process a PO, Q to quit.\n";
    while (cin>>ch&&toupper(ch)!='Q')
    {
        while(cin.get()!='\n')//若是不是換行就繼續
            continue;
        if (!isalpha(ch))//若是不是字母就繼續
        {
            cout<<'\a';
            continue;
        }
        switch (ch)
        {
        case 'A':
        case 'a':
            cout<<"Enter a PO number to add: ";
            cin>>po;
            if(st.isfull())//該方法判斷:若是滿了(top等於MAX)返回true,沒滿返回false
                cout<<"Stack already full\n";
            else
                st.push(po);
            break;
        case 'P':
        case 'p':
            if(st.isempty())
                cout<<"Stack already empty\n";
            else{
                st.pop(po);
                cout<<"PO #"<<po<<" popped\n";
            }
            break;
        }
        cout<<"Enter A to add a purchase order, P to process a PO, Q to quit.\n";
    }
    system("pause");
}

相關文章
相關標籤/搜索