C++ Primer Plus 第六版 第十二章 练习题参考答案

//1.************************************
//cow.h
#ifndef COW_H_
#define COW_H_
#include<iostream>

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_H_
//cow.cpp
#include<iostream>
#include<cmath>
#include"cow.h"
#include<cstdlib>

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

Cow & Cow::operator=(const Cow & c)
{
    if (this == &c)
        return *this;
    strcpy_s(name, strlen(c.name) + 1, c.name);
    delete[] hobby;
    hobby = new char[strlen(c.hobby) + 1];
    strcpy_s(hobby, strlen(c.hobby) + 1, c.hobby);
    weight = c.weight;
    return *this;
}

void Cow::showcow() const
{
    std::cout << "name: ";
    for (int i = 0; i < strlen(name); i++)
        std::cout << name[i];
    std::cout << "\n";
    std::cout << "hobby: ";
    for (int i = 0; i < strlen(hobby); i++)
        std::cout << hobby[i];
    std::cout << "\n";
    std::cout << "weight: " << weight << "\n";
}
//main.cpp
#include <iostream>
#include <cstdlib>     //rand,srand() prototypes
#include <ctime>   //time() prototype
#include<stdlib.h>
#include "cow.h"   
using std::cout;
using std::endl;
using std::cin;

int main()
{
    Cow c1;
    Cow c2("X", "Ring", 10.2);
    Cow c3(c2);
    c1 = c2;
    cout << "c1:\n";
    c1.showcow();
    cout << "c2:\n";
    c2.showcow();
    cout << "c3:\n";
    c3.showcow();
    system("pause");
    return 0;
}
//2***************************************
//string2.h
#ifndef String2_H_
#define String2_H_
#include<iostream>
using std::ostream;
using std::istream;
class String
{
private:
    char *str;
    int len;
    static const int CINLIM = 80;
public:
    String(const char *s);
    String();
    String(const String &);
    ~String();
    int length() const { return len; }
    String & operator=(const String &);
    String & operator=(const char * s);
    String & operator+(const String &);
    void stringlow();
    void string();
    int chcount(char a);
    char &operator[] (int i);
    const char &operator[](int i) const;
    friend bool operator<(const String &st, const String &st2);
    friend bool operator>(const String &st1, const String &st2);
    friend bool operator==(const String &st, const String &st2);
    friend ostream & operator<<(ostream & os, const String & st);
    friend String & operator+(const char *a,String &s);
    friend String & operator+(String &s, const char *a);
    friend istream & operator >> (istream & is,  String &st);
};
#endif // String2_H_
//string2.cpp
#include<iostream>
#include<cmath>
#include"string2.h"
#include<cstdlib>

String::String(const char * s)
{
    len = strlen(s);
    str = new char[len + 1];
    strcpy_s(str, len+1, s);
}

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

String::String(const String &s)
{
    len = s.len;
    str = new char[len + 1];
    strcpy_s(str, len+1, s.str);
}

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

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

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

String & String::operator+(const String & st)
{
    len += st.len;
    char *temp = new char[len+1];
    strcpy_s(temp, len+1,str);
    delete[]str;
    str = new char[len + 1];
    strcpy_s(str, len + 1, temp);
    delete[]temp;
    strcat_s(str, len + 1, st.str);
    return *this;
}


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

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

int String::chcount(char a)
{
    int chcount = 0;
    for (int i = 0; i < len; ++i)
        if (str[i] == 'a'||str[i]=='A')
            chcount++;
    return chcount;
}

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

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

bool operator<(const String & st, const String & st2)
{
    return (std::strncmp(st.str, st2.str, 80)<0);
}
bool operator>(const String &st, const String & st2)
{
    return st2 < st;
}

bool operator==(const String & st, const String & st2)
{
    return (strncmp(st.str, st2.str,80) == 0);
}

ostream & operator<<(ostream & os, const String & st)
{
    os << st.str;
    return os;
}

String & operator+(const char * a, String &s)
{
    char *temp = new char[s.len + 1 + strlen(a)];
    strcpy_s(temp, s.len + 1 + strlen(a), a);
    strcat_s(temp, s.len + 1 + strlen(a), s.str);
    delete[]s.str;
    s.str = new char[s.len + 1 + strlen(a)];
    strcpy_s(s.str, s.len + 1 + strlen(temp), temp);
    s.len = strlen(s.str);
    return s;
}

String & operator+(String & s,const char * a)
{
    char *temp = new char[s.len + 1 + strlen(a)];
    strcpy_s(temp, s.len + 1 + strlen(a), a);
    strcat_s(temp, s.len + 1 + strlen(a), s.str);
    delete[]s.str;
    s.str = new char[s.len + 1 + strlen(a)];
    strcpy_s(s.str, s.len + 1+strlen(temp), temp);
    s.len = strlen(s.str);
    return s;
}

istream & operator >> (istream & is, String & st)
{
    char temp[String::CINLIM];
    is.get(temp, String::CINLIM);
    if (is)
        st = temp;
    while (is&&is.get() != '\n')
        continue;
    return is;
}
//main.cpp
#include <iostream>
#include <cstdlib>     //rand,srand() prototypes
#include <ctime>   //time() prototype
#include<stdlib.h>
#include "string2.h"   
using std::cout;
using std::endl;
using std::cin;

int main()
{
    String s1(" and I am a C++ Student. ");
    String s2 = "Please enter your name: ";
    String s3;
    cout << s2;
    cin >> s3;
    s2 = "My name is " + s3;
    s2 = s2 + s1;
    cout << s2 << " .\n";
    s2.string();
    cout << "The string\n" << s2 << "\ncontains " << s2.chcount('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>
using std::ostream;
using std::istream;
class Stock
{
private:
    char * company;
    int len;
    int shares;
    double share_val;
    double total_val;
    void set_tot() { total_val = shares * share_val; };
public:
    Stock();
    Stock(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 ostream &operator<<(ostream &os,char *ch);
    friend ostream & operator<< (ostream &os,const Stock &s);
};
#endif_
//stock.cpp
#include<iostream>
#include<cmath>
#include"stock.h"
#include<cstdlib>

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

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

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

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)
{
    using std::cout;
    if (num < 0)
    {
        cout << "Number of shares sold can't be negative.Transaction is aborted.\n";
    }
    else if (num > shares)
    {
        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;
}


ostream & operator<<(ostream & os, char * ch)
{
    for (int i = 0; i < strlen(ch); ++i)
        os << ch[i];
    return os;
}

ostream & operator<<(ostream & os,const Stock & s)
{
    os << "the Stock information of " << s.company << "\n";
    os << "Name: " << s.company << std::endl;
    os << "shares: " << s.shares;
    os << "share_val: " << s.share_val;
    os << "total_val: " << s.total_val;
    return os;
}
//main.cpp
#include <iostream>
#include <cstdlib>     //rand,srand() prototypes
#include <ctime>   //time() prototype
#include<stdlib.h>
#include "stock.h"   
using std::cout;
using std::endl;
using std::cin;
const int STKS = 4;
int main()
{   
    Stock stocks[STKS]{
        Stock("NanoSmart",12,20.0),
        Stock("Boffo Obejects",200,2.0),
        Stock("Monolithic Obelisk",130,3.25),
        Stock("Fleep Enterprises",60,6.5)
    };
    cout << " Stock holdings:\n";
    int st;
    for (st = 0; st < STKS; st++)
        cout << stocks[st];
    const Stock *top = &stocks[0];
    for (st = 1; st < STKS; st++)
        top = &top->topval(stocks[st]);
    cout << "\nMost valuable holdings:\n";
    cout << (*top);
    system("pause");
    return 0;
}
//4**************************************
#ifndef STACK_H_
#define STACK_H_
#include<iostream>
using std::ostream;
using std::istream;
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_H_
//stack.cpp
#include<iostream>
#include<cmath>
#include"stack.h"
#include<cstdlib>

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

Stack::Stack(const Stack & st)
{
    size = st.size;
    pitems = new Item[size+1];
    pitems = st.pitems;
    top = st.top;
}

Stack::~Stack()
{
    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;
    else
    {
        pitems[top++] = item;
        return true;
    }
}

bool Stack::pop(Item & item)
{
    if(isempty())
        return false;
    else
    {
        item = pitems[--top];
        return true;
    }
}

Stack & Stack::operator=(const Stack & st)
{
    delete[] pitems;
    size = st.size;
    pitems = new Item[size];
    pitems = st.pitems;
    top = st.top;
    return *this;
}
//main.cpp
#include <iostream>
#include <cstdlib>     //rand,srand() prototypes
#include <ctime>   //time() prototype
#include<stdlib.h>
#include "stack.h"   
using std::cout;
using std::endl;
using std::cin;
int main()
{   
    Stack st(2);
    char ch;
    unsigned long po;
    cout << "Please enter A to add a purchase order,\n"
        << "P to process a PO,or 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())
                        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 << "Please enter A to add a customer,\n"
            << "P to process a customer, and Q to quit.\n";
    }
    Stack st1 = st;
    if (st1.isfull())
        cout << " stack #1 now is full.\n";
    else
        cout << "stack #1 is capabled to push.\n";
    system("pause");
    return 0;
}
//5,6略.
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,744评论 6 502
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,505评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 163,105评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,242评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,269评论 6 389
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,215评论 1 299
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,096评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,939评论 0 274
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,354评论 1 311
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,573评论 2 333
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,745评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,448评论 5 344
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,048评论 3 327
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,683评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,838评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,776评论 2 369
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,652评论 2 354