C++ primer第6版 12章课后题

12.1 对于下面的类声明:

class Cow{
    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; //display all cow data    
};

给这个类提供实现,并编写一个使用所有类成员函数的小程序。

class Cow{
    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; //display all cow data
};

Cow::Cow(){
    name[0] = '\0';
    hobby = new char[1];
    weight = 0.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(){
    delete []hobby;
}

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

void Cow::ShowCow() const{
    cout<<"Name = "<<name<<endl<<"Hobby: "<<hobby<<endl<<"Weight: "<<weight<<endl;
}

2.通过完成下面的工作来改进String类声明:
a.对+运算符进行重载,使之可将两个字符串合并成1个
b.提供一个Stringlow()成员函数,将字符串中所有的字母字符转换为小写(别忘了存储type系列字符函数)。
c.提供String()成员函数,将字符串中所有字母字符转换成大写。
d.提供一个这样的成员函数,它接受一个char参数,返回该字符在字符串中出现的次数
头文件

//
//  string1.h
//  12.2
//
//  Created by apple on 2018/8/13.
//  Copyright © 2018年 apple. All rights reserved.
//

#ifndef string1_h
#define string1_h
#include <iostream>
using namespace std;

class String {
private:
    char* str;
    int len;
    static int num_strings;//number of objects
    static const int CINLIM = 80; //cin input limits
public:

    String(const char* s);
    String();//default constructor
    String(const String &);//copy constructor
    ~String();
    int length()const{return len;}
    //overloaded operator methods
    String& operator=(const String &);
    String& operator=(const char*);
    String operator+(const String &)const;//merge
    String operator+(const char*);//merge
    char& operator[](int i);
    const char& operator[](int i) const;
    //overloaded operator friends
    friend bool operator<(const String &st, const String &str2);
    friend bool operator>(const String &st, const String &str2);
    friend bool operator==(const String &st, const String &str2);
    friend ostream & operator<<(ostream &os, const String &str);
    friend istream & operator>>(istream &is, const String &str);
    friend String operator+(char *st, const String&s);
    //static function
    static int HowMany();

    String stringlow();
    String stringup();
    int has(char );
};

#endif /* string1_h */

头文件实现文件

//
//  string1.cpp
//  12.2
//
//  Created by apple on 2018/8/13.
//  Copyright © 2018年 apple. All rights reserved.
//

#include <stdio.h>
#include "string1.h"
using namespace std;

int String::num_strings = 0;
String::String(const char* s){
    len = strlen(s);//set size
    str = new char(len);//allot storage
    strcpy(str,s);//initialize pointer
    num_strings++;//set object count
}

String::String(){
    //default constructor
    len = 4;
    str = new char[1];
    str[0] = '\0'; //default string;
    num_strings++;
}
String::String(const String &st){
    //copy constructor
    num_strings++;
    len = st.len;//same length
    str = new char(len + 1);//allot space
    strcpy(str, st.str);//copy string to new location
}
String::~String(){
    --num_strings;
    delete []str;
}

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

}
String& String::operator=(const char*s){
    delete []str;
    len = strlen(s);
    str = new char[len+1];
    strcpy(str,s);
    return *this;
}
char& String::operator[](int i){
    return str[i];
}
const char& String::operator[](int i) const{
    return str[i];
}
//overloaded operator friends
bool operator<(const String &st, const String &str2){
    return (strcmp(st.str, str2.str)<0);
}
bool operator>(const String &st, const String &str2){
    return (strcmp(st.str, str2.str)>0);
}
bool operator==(const String &st, const String &str2){
    return (strcmp(st.str, str2.str)== 0);
}
ostream & operator<<(ostream &os, const String &st){
    os<<st.str;
    return os;
}
istream & operator>>(istream & is, String & st){
    char tmp[String::CINLIM];
    is.get(tmp, String::CINLIM);
    if(is)
        st = tmp;
    while (is && is.get()!='\n')
        continue;
    return is;
}
//static function
int String::HowMany(){
    return num_strings;
}

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

String String::stringlow(){
    int i = 0;
    while (i < len) {
        str[i++] = tolower(str[i]);
    }
    return *this;
}

String String::stringup(){
    int i = 0;
    while (i < len) {
        str[i++] = toupper(str[i]);
    }
    return *this;
}

int String::has(char a){
    int count = 0;
    for(int i =0 ; i < len; i++){
        if(str[i] == a)
            count++;
    }
    return count;
}

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

测试文件

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

const int ArSize = 10;
const int MaxLen = 81;
int main(){
    String s1("and I am a C++ Student.");
    String s2 = "Please enter your name:";
    String s3 = "cin mei xie hao";
    cout<<s2;//overload << operator
 //   cin>>s3;//overload >> operator
    s2 = "My name is " + s3; // overloaded =, + operators
    cout<< s2<<".\n";
    s2 = s2+s1;
    s2.stringup(); //converts string to uppercase
    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";
    return 0;
}

3.新编写程序清单10.7和程序清单10.8描述的Stock类,使之使用动态分配的内存,而不是string类对象来存储股票名称。另外,使用重载的operator<<()定义代替show()成员函数,再使用程序清单10.9测试新的定义程序。
头文件

//
//  Stock.h
//  12.3
//
//  Created by apple on 2018/8/13.
//  Copyright © 2018年 apple. All rights reserved.
//

#ifndef Stock_h
#define Stock_h
#include <string>

class Stock{
private:
    char *company;
    int shares;
    double shared_val;
    double total_val;
    void set_tot(){
        total_val = shares*shared_val;
    }
public:
    Stock();
    Stock(const char *, 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;
    friend std::ostream & operator <<(std::ostream &os, const Stock &s);
    const Stock& topval(const Stock &s) const;
};

#endif /* Stock_h */

头文件实现文件

//
//  Stock.cpp
//  12.3
//
//  Created by apple on 2018/8/13.
//  Copyright © 2018年 apple. All rights reserved.
//

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

Stock::Stock(){
    company = new char[8];
    char *s = "no name";
    strcpy(company, s);
    shares = 0;
    shared_val = 0.0;
    total_val = 0.0;
}

Stock::Stock(const char *s, long n , double pr ){
    int len = strlen(s);
    company = new char[len+1];
    strcpy(company, s);
    if(n < 0){
        cout<<"Number of shares can't be negative; "<<company<<" shares set to 0.\n";
        shares = 0;
    }
    else
        shares = n;
    shared_val = pr;
    set_tot();
}
Stock::~Stock(){
    delete []company;
}
void Stock::buy(long num, double price){
    if(num < 0){
        cout<<"Number of shares purchased can't be negative. "<<"Transaction is aborted.\n";
    }
    else{
        shares += num;
        shared_val = price;
        set_tot();
    }
}

void Stock::sell(long num, double price){
    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;
        shared_val = price;
        set_tot();
    }
}

void Stock::update(double price){
    shared_val = price;
    set_tot();
}
/*void Stock::show()const{
    //set format to #.###
    ios_base::fmtflags orig = cout.setf(ios_base::fixed, ios_base::floatfield);
    streamsize prec = cout.precision(3);
    cout<<"Company: "<<company<<" Shares: "<<shares<<'\n';
    cout<<" Share Price: $"<<shared_val;
    //set format to #.##
    cout.precision(2);
    cout<<" Total Worth: $"<<total_val<<'\n';

    //restore original format
    cout.setf(orig, ios_base::floatfield);
    cout.precision(prec);
}*/
std::ostream & operator <<(std::ostream &os, const Stock &s){
    //set format to #.###
    ios_base::fmtflags orig = cout.setf(ios_base::fixed, ios_base::floatfield);
    streamsize prec = cout.precision(3);
    cout<<"Company: "<<s.company<<" Shares: "<<s.shares<<'\n';
    cout<<" Share Price: $"<<s.shared_val;
    //set format to #.##
    cout.precision(2);
    cout<<" Total Worth: $"<<s.total_val<<'\n';

    //restore original format
    cout.setf(orig, ios_base::floatfield);
    cout.precision(prec);
    return os;
}

const Stock& Stock::topval(const Stock &s) const{
    if(s.total_val > total_val){
        return s;
    }
    else
        return *this;
}

测试文件

//
//  main.cpp
//  12.3
//
//  Created by apple on 2018/8/13.
//  Copyright © 2018年 apple. All rights reserved.
//

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

const int STKS = 4;

int main(int argc, const char * argv[]) {
    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)
    };
    cout<<"Stock holding:\n";
    int st;
    for(st = 0; st < STKS; st++){
       // stocks[st].show();
        cout<<stocks[st];
    }
    const Stock *top = &stocks[0];
    for(st = 1; st < STKS; st++){
        top = &top->topval(stocks[st]);
    }
    cout<<"\n Most valuable holding:\n";
   // top->show();
    cout<<*top;
    return 0;
}

4.

//
//  main.cpp
//  12.4
//
//  Created by apple on 2018/8/14.
//  Copyright © 2018年 apple. All rights reserved.
//

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

int main(int argc, const char * argv[]) {
    Stack st1(10);
    srand(time(0));
    for(size_t i = 0; i < 10; i++){
        if(!st1.push(rand()%100)){
            cout<<"Push error!"<<endl;
        }
    }
    if(!st1.push(0)){
        cout<<"Push 0 error!"<<endl;
    }
    Stack st2(st1);
    Stack st3 = st1;
    //故意设置pop error
    for(size_t i = 0; i < 11; i++){
        Item item;
        cout<<"#"<<i+1<<": "<<endl;
        if(!st1.pop(item)){
            cout<<"st1 pop error! "<<endl;
        }
        else{
            cout<<"st1: "<<item<<endl;
        }
        if(!st2.pop(item)){
            cout<<"st2 pop error!"<<endl;
        }
        else{
            cout<<"st2: "<<item<<endl;
        }
        if(!st3.pop(item)){
            cout<<"st3 pop error!"<<endl;
        }
        else
            cout<<"st3: "<<item <<endl;
    }
    return 0;
}

6.Heather银行想知道,如果再开设一台ATM,情况将如何。请对模拟进行修改,以包含两个队列。假设当第一台ATM前的排队人数少于第二台ATM时,客户讲排在第一队,否则将排在第二队。然后再找出要使品骏等候时间为1分钟,每小时到达的客户数应该为多少?

//
//  main.cpp
//  12.5
//
//  Created by apple on 2018/8/14.
//  Copyright © 2018年 apple. All rights reserved.
//

#include <iostream>
#include "queue.h"
const int MIN_PER_HR = 60;
bool newcustomer(double x);
using namespace std;

int main(int argc, const char * argv[]) {
    srand(time(0));//random initializing of rand()
    cout<<"Case Study: Bank of Heather Automatic Teller.\n";
    cout<<"Enter maximum size of queue: ";
    int qs;
    cin>>qs;
    Queue line1(qs);
    Queue line2(qs);
    cout<<"Enter the number of simulation hours: ";
    int hours;
    cin>>hours;
    //simulation will run 1 cycle per minute
    long cyclelimit = MIN_PER_HR * hours;

    cout<<"Enter the average number of customers per hour: ";
    double perhour;
    cin>>perhour;
    double min_per_cust;
    min_per_cust = MIN_PER_HR;

    Item temp; // new customer data
    long turnaways = 0; //turned away by full queue
    long cusstomers = 0; //joined the queue
    long served = 0; //served during the simulation
    long sum_line = 0; //cumulative line length
    int wait_time1 = 0; //time until autoteller is free
    int wait_time2 = 0;
    long line_wait = 0; //cumulative time in line
    //running the simulation
    for(int cycle = 0; cycle < cyclelimit; cycle++){
        if(newcustomer(min_per_cust)){
            if(line1.isfull() && line2.isfull())
                turnaways++;
            else{
                cusstomers++;
                temp.set(cycle);
                if(line1.queuecount() < line2.queuecount()){
                    line1.enqueue(temp);
                }
                else{
                    line2.enqueue(temp);
                }

            }
        }
        if(wait_time1 <= 0 && !line1.isempty()){
            line1.dequeue(temp);
            wait_time1 = temp.ptime();
            line_wait += cyclelimit - temp.when();
            served++;
        }
        if(wait_time2 <= 0 && !line2.isempty()){
            line2.dequeue(temp);
            wait_time2 = temp.ptime();
            line_wait += cyclelimit - temp.when();
            served++;
        }
        if(wait_time1 > 0)
            wait_time1--;
        if(wait_time2 > 0)
            wait_time2--;
        sum_line += (line1.queuecount() + line2.queuecount())/2;
    }
    //reporting results
    if(cusstomers > 0){
        cout<<"customers accepted: "<<cusstomers<<endl;
        cout<<" customers served: "<<served<<endl;
        cout<<"     turnaways: "<<turnaways<<endl;
        cout<<"average queue size: ";
        cout.precision(2);
        cout.setf(ios_base::fixed, ios_base::floatfield);
        cout<<(double) sum_line / cyclelimit << endl;
        cout<<" average wait time: "<<(double) line_wait / served << " minutes\n";
    }
    else{
        cout<<"No customers!\n";
    }
    cout<<"Done!\n";
    return 0;
}

bool newcustomer(double x){
    return (std::rand() * x / RAND_MAX < 1);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值