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;
}

猜你喜欢

转载自blog.csdn.net/xiaomimi1993/article/details/81631224
今日推荐