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略.
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。