第十二章 编程练习

这章开始编程练习都好长,敲都要敲半天。。。
编程练习1

//Cow.h
#ifndef COW_H_
#define COW_H_
class Cow
{
private:
    char name[20];
    char * hobby;
    double weight;
public:
    Cow();
    Cow(const char * nm, const char * ho, double wt);
    Cow(const Cow &c);
    ~Cow();
    Cow & operator=(const Cow & c);
    void ShowCow() const;
};
#endif
//Cow.cpp
#include "Cow.h"
#include <cstring>
#include <iostream>
using namespace std;

Cow::Cow()
{
    strcpy(name,"");
    hobby = new char[1];
    hobby[0] = '\0';
    weight = 0;
}
Cow::Cow(const char * nm, const char * ho, double wt)
{
    strcpy(name, nm);
    hobby = new char[strlen(ho)+1];
    strcpy(hobby, ho);
    weight = wt;
}
Cow::Cow(const Cow &c)
{
    strcpy(name, c.name);
    hobby = new char[strlen(c.hobby)+1];
    strcpy(hobby, c.hobby);
    weight = c.weight;
}

Cow::~Cow(void)
{
    delete [] hobby;
}

Cow & Cow::operator=(const Cow & c)
{
    if (this == &c)
        return *this;
    strcpy(name, c.name);
    delete [] hobby;
    hobby = new char[strlen(c.hobby)+1];
    strcpy(hobby, c.hobby);
    weight = c.weight;
    return *this;
}
void Cow::ShowCow() const
{
    cout << "Cow's name is "<< name
        << "; Cow's hobby is " << hobby
        << "; Cow's weight is " << weight
        << endl;
}
//main.cpp
#include "Cow.h"
#include <iostream>

int main()
{
    {
        Cow cow1;
        Cow cow2("yellow cow", "sleep", 2000);
        Cow cow3(cow2);
        cow1 = cow2;
        cow1.ShowCow();
        cow2.ShowCow();
        cow3.ShowCow();
    }
    system("pause");
    return 0;
}

编程练习2
这里的两个string的加法运算符重载可以好好品味一下

//string2.h
#ifndef STRING2_H_
#define STRING2_H_
#include <iostream>
using std::ostream;
using std::istream;

class String
{
private:
    char *str;
    int len;
    static int num_Strings;
    static const int CLNLIM = 80;
public:
    String();
    ~String();
    String(const char *s);
    String(const String &);
    int length () const {return len;}

    String & operator=(const String &);
    String & operator=(const char *);
    char & operator[] (int i);
    const char & operator[] (int i) const;

    friend bool operator<(const String &st1, const String &st2);
    friend bool operator>(const String &st1, const String &st2);
    friend bool operator==(const String &st1, const String &st2);
    friend String operator+(const String &st1, const String &st2);

    friend ostream & operator<<(ostream & os, const String & st);
    friend istream & operator>>(istream & is, String & st);

    void StringLow();
    void StringUp();
    int has(char c);
};
#endif
//string2.cpp
#include "String2.h"
#include <cstring>
using std::cin;
using std::cout;

int String::num_Strings = 0;
String::String(void)
{
    len = 4;
    str = new char[1];
    str[0] = '\0';
    num_Strings++;
}


String::~String(void)
{
    --num_Strings;
    delete [] str;
}

String::String(const char *s)
{
    len = std::strlen(s);
    str = new char[len+1];
    std::strcpy(str, s);
    num_Strings++;
}
String::String(const String &st)
{
    num_Strings++;
    len = st.len;
    str = new char[len+1];
    std::strcpy(str, st.str);
}

String & String::operator=(const String &st)
{
    if (this==&st)
        return *this;
    delete [] str;
    len = st.len;
    str = new char[len+1];
    std::strcpy(str, st.str);
    return *this;
}
String & String::operator=(const char *s)
{
    delete [] str;
    len = std::strlen(s);
    str = new char[len+1];
    std::strcpy(str, s);
    return *this;
}

char & String::operator[] (int i)
{
    return str[i];
}
const char & String::operator[] (int i) const
{
    return str[i];
}

bool operator<(const String &st1, const String &st2)
{
    return (std::strcmp(st1.str, st2.str) < 0);
}
bool operator>(const String &st1, const String &st2)
{
    return st2 < st1;
}
bool operator==(const String &st1, const String &st2)
{
    return (std::strcmp(st1.str, st2.str) == 0);
}
String operator+(const String &st1, const String &st2)
{
    String s;
    s.len = st1.len + st2.len;
    s.str = new char[s.len + 1];
    strcpy(s.str, st1.str);
    strcat(s.str, st2.str);
    return s;
}

ostream & operator<<(ostream & os, const String & st)
{
    os << st.str;
    return os;
}
istream & operator>>(istream & is, String & st)
{
    char temp[String::CLNLIM];
    is.get(temp, String::CLNLIM);
    if(is)
        st = temp;
    while (is && is.get() != '\n')
        continue;
    return is;
}

void String::StringLow()
{
    for(int i=0;i<len;i++)  
        str[i]=tolower(str[i]);  
}
void String::StringUp()
{
    for(int i=0;i<len;i++)  
        str[i]=toupper(str[i]);  
}

int String::has(char c)
{
    int num = 0;
    for(int i=0;i<len;i++) 
    {
        if (str[i]==c)
            num++;
    }
    return num; 
}
//main.cpp
#include <iostream>
using namespace std;
#include "String2.h"

int main()
{
    String s1(" and I am a C++ student.");
    String s2 = "Please enter your name: ";
    String s3;
    cout << s2;
    cin >> s3;
    //s2 = s1+s3;
    s2 = "My name is " + s3;
    cout << s2 << ".\n";
    s2 = s2 + s1;
    s2.StringUp();
    cout << "The String\n" << s2 << "\ncontains " << s2.has('A')
        << " 'A' characters in it.\n";
    s1 = "red";

    String rgb[3] = {String(s1), String("green"), String("blue")};
    cout << "Enter the name of a primary color for mixing light: ";
    String ans;
    bool success = false;
    while (cin >> ans)
    {
        ans.StringLow();
        for (int i = 0; i<3; i++)
        {
            if (ans == rgb[i])
            {
                cout << "That's right!\n";
                success = true;
                break;
            }
        }
        if (success)
            break;
        else
            cout << "Try again!\n";
    }
    cout << "Bye\n";
    system("pause");
    return 0;
}

编程练习3

//Stock.h
#ifndef STOCK_H_
#define STOCK_H_
#include <iostream>
class Stock
{
private:
    char *company;
    int shares;
    double share_val;
    double total_val;
    void set_tot() { total_val = shares * share_val; }
public:
    Stock();
    Stock(const char *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);
    const Stock &topval(const Stock &s) const;
    friend std::ostream &operator<<(std::ostream &os, const Stock &s);
};
#endif
//Stock.cpp
#include "Stock.h"

Stock::Stock()
{
    company = new char[1];
    company[0] = '\0';
    shares = 0;
    share_val = 0;
    set_tot();
}

Stock::~Stock()
{
    delete [] company;
}

Stock::Stock(const char *co, long n, double pr)
{
    int len = strlen(co);
    company = new char[len+1];
    strcpy(company, co);
    if (n < 0)
    {
        std::cout << "Number of shares can't be negative; "
            << company << " shares set to 0.\n";
        shares = 0;
    }
    else
        shares = n;
    share_val = pr;
    set_tot();
}

void Stock::buy(long num, double price)
{
    if (num < 0)
    {
        std::cout << "Number of shares purchased can't be negative. "
            << "Transaction is aborted. \n";
    }
    else
    {
        shares += num;
        share_val = price;
        set_tot();
    }
}
void Stock::sell(long num, double price)
{
    if (num < 0)
    {
        std::cout << "Number of shares sold can't be negative. "
            << "Transaction is aborted.\n";
    }
    else if (num > shares)
    {
        std::cout << "You can't sell more than you have! "
            << "Transaction is aborted.\n";
    }
    else
    {
        shares -= num;
        share_val = price;
        set_tot();
    }
}
void Stock::update(double price)
{
    share_val = price;
    set_tot();
}
const Stock & Stock::topval(const Stock &s) const
{
    if (s.total_val > total_val)
        return s;
    else
        return *this;
}
std::ostream &operator<<(std::ostream &os, const Stock &s)
{
    std::ios_base::fmtflags orig = os.setf(std::ios_base::fixed, std::ios_base::floatfield);
    std::streamsize prec = os.precision(3);

    os << "Company: " << s.company << "  Shares: " << s.shares << '\n';
    os << "  Share Price: $" << s.share_val;
    os.precision(2);
    os << "  Total Worth: $" << s.total_val << '\n';

    os.setf(orig, std::ios_base::floatfield);
    os.precision(prec);
    return os;
}
//main.cpp
#include "stock.h"
#include <iostream>

const int STKS = 4;

int main()
{
    Stock stocks[STKS] = {
        Stock("NanoSmart", 12, 20.0),
        Stock("Boffo Objects", 200, 2.0),
        Stock("Monolithic, Obelisks", 130, 3.25),
        Stock("Fleep Enterprises", 60, 6.5)
    };
    std::cout << "Stock holdings:\n";
    int st;
    for (st = 0; st < STKS; ++st)
        std::cout << stocks[st];
    const Stock *top = &stocks[0];
    for (st = 1; st < STKS; ++st)
        top = &top->topval(stocks[st]);
    std::cout << "\nMost valuable holding: \n";
    std::cout << (*top);
    system("PAUSE");
    return 0;
}

编程练习4

//Stack.h
#ifndef STACK_H_
#define STACK_H_

#include <iostream>
typedef unsigned long Item;
class Stack
{
private:
    enum { MAX = 10};
    Item *pitems;
    int size;
    int top;
public:
    Stack(int n = MAX);
    Stack(const Stack &st);
    ~Stack();
    bool isempty() const;
    bool isfull() const;
    bool push(const Item &item);
    bool pop(Item &item);
    Stack &operator=(const Stack &st);

};
#endif
//Stack.cpp
#include "Stack.h"

Stack::Stack(int n)
{
    pitems = new Item[1];
    pitems[0] = '\0';
    size = n;
    top = 0;;
}

Stack::Stack(const Stack &st)
{
    pitems = new Item(st.size);
    size = st.size;
    for (top = 0; top < size; ++top)
        pitems[top] = st.pitems[top];
}
Stack::~Stack(void)
{
    delete [] pitems;
}

bool Stack::isempty() const
{
    return top == 0;
}
bool Stack::isfull() const
{
    return top == size;
}

bool Stack::push(const Item &item)
{
    if (isfull())
        return false;
    pitems[top++] = item;
    return true;
}
bool Stack::pop(Item &item)
{
    if (isempty())
        return false;
    --top;
    return true;
}
Stack & Stack::operator=(const Stack &st)
{
    if (this == &st)
        return *this;
    pitems = new Item(st.size);
    size = st.size;
    for (top = 0; top < size; ++top)
        pitems[top] = st.pitems[top];
    return *this;
}
//main.cpp
#include "stack.h"

int main()
{
    Stack s(10);

    std::cout << s.isempty() << std::endl;
    s.push(100);
    std::cout << s.isempty() << std::endl;

    system("pause");
    return 0;
}

编程练习5,可以直接用书中的例子来测试了, 编程练习6 稍微更改一下主函数再添加一个queue对象然后添加一些操作即可,这里就不贴出来了.但是这是一个很好的队列的练习;在读完本书之后可以回过头来好好分析一下.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值