编程练习答案——第12章

【C++ Primer Plus】编程练习答案——第12章

 1 // chapter12_1_cow.h
 2 
 3 
 4 #ifndef LEARN_CPP_CHAPTER12_1_COW_H
 5 #define LEARN_CPP_CHAPTER12_1_COW_H
 6 
 7 class Cow {
 8 private:
 9     char name_[20];
10     char * hobby_;
11     double weight_;
12 public:
13     Cow();
14     Cow(const char * name, const char * hobby, double weight);
15     Cow(const Cow & c);
16     ~Cow();
17     Cow & operator=(const Cow & c);
18     void showcow() const;
19 };
20 
21 
22 #endif //LEARN_CPP_CHAPTER12_1_COW_H
23 
24 
25 // chapter12_1_cow.cpp
26 
27 #include "chapter12_1_cow.h"
28 #include <cstring>
29 #include <iostream>
30 
31 Cow::Cow() {
32     name_[0] = "";
33     hobby_ = nullptr;
34     weight_ = 0;
35 }
36 
37 Cow::Cow(const char * name, const char * hobby, double weight) {
38     strcpy(name_, name);
39     hobby_ = new char[strlen(hobby)];
40     strcpy(hobby_, hobby);
41     weight_ = weight;
42 }
43 
44 Cow::Cow(const Cow &c) {
45     strcpy(name_, c.name_);
46     if (!hobby_) delete [] hobby_;
47     hobby_ = new char[strlen(c.hobby_)];
48     strcpy(hobby_, c.hobby_);
49     weight_ = c.weight_;
50 }
51 
52 Cow::~Cow() {
53     delete [] hobby_;
54 }
55 
56 Cow & Cow::operator=(const Cow & c) {
57     strcpy(name_, c.name_);
58     if (!hobby_) delete [] hobby_;
59     hobby_ = new char[strlen(c.hobby_)];
60     strcpy(hobby_, c.hobby_);
61     weight_ = c.weight_;
62     return *this;
63 }
64 
65 void Cow::showcow() const {
66     using namespace std;
67     cout << "name: " << name_ << endl
68         << "hobby: " << hobby_ << endl
69         << "weight: " << weight_ << endl;
70 }
71 
72 // run
73 
74 void ch12_1() {
75     Cow a("nma", "tennis", 70);
76     Cow b("nmb", "football", 65);
77     a.showcow();
78     b.showcow();
79     b = a;
80     b.showcow();
81     Cow c(a);
82     c.showcow();
83 }
hmoban主题是根据ripro二开的主题,极致后台体验,无插件,集成会员系统
自学咖网 » 编程练习答案——第12章