├── README.md ├── cpp_primer_plus_code ├── myCode │ ├── 6 │ │ ├── 1 │ │ │ └── main1.cpp │ │ ├── 2 │ │ │ └── main1.cpp │ │ ├── 3 │ │ │ └── main1.cpp │ │ ├── 4 │ │ │ └── main1.cpp │ │ ├── 5 │ │ │ └── main1.cpp │ │ ├── 6 │ │ │ └── main1.cpp │ │ ├── 7 │ │ │ └── main1.cpp │ │ ├── 8 │ │ │ └── main1.cpp │ │ └── 9 │ │ │ ├── donation.txt │ │ │ └── main1.cpp │ ├── 7 │ │ ├── 1 │ │ │ └── main.cpp │ │ ├── 2 │ │ │ └── main.cpp │ │ ├── 3 │ │ │ └── main.cpp │ │ ├── 4 │ │ │ └── main.cpp │ │ ├── 5 │ │ │ └── main.cpp │ │ ├── 6 │ │ │ └── main.cpp │ │ ├── 7 │ │ │ └── main.cpp │ │ └── 8 │ │ │ ├── a │ │ │ └── main.cpp │ │ │ └── b │ │ │ └── main.cpp │ ├── 8 │ │ ├── 1 │ │ │ └── 源.cpp │ │ ├── 2 │ │ │ └── 源.cpp │ │ ├── 3 │ │ │ └── 源.cpp │ │ ├── 5 │ │ │ └── 源.cpp │ │ └── 6 │ │ │ └── 源.cpp │ ├── 10 │ │ ├── 1 │ │ │ ├── bank.cpp │ │ │ ├── bank.h │ │ │ └── 源.cpp │ │ ├── 2 │ │ │ └── main.cpp │ │ ├── 3 │ │ │ ├── golf.cpp │ │ │ ├── golf.h │ │ │ └── main.cpp │ │ ├── 4 │ │ │ ├── main.cpp │ │ │ ├── sale.cpp │ │ │ └── sale.h │ │ ├── 6 │ │ │ ├── main.cpp │ │ │ ├── move.cpp │ │ │ └── move.h │ │ └── 7 │ │ │ ├── main.cpp │ │ │ ├── plorg.cpp │ │ │ └── plorg.h │ ├── 11 │ │ ├── 3 │ │ │ ├── vect.cpp │ │ │ ├── vect.h │ │ │ └── 源.cpp │ │ ├── 4 │ │ │ ├── main.cpp │ │ │ ├── time.cpp │ │ │ └── time.h │ │ ├── 5 │ │ │ ├── stonewt.cpp │ │ │ ├── stonewt.h │ │ │ └── 源.cpp │ │ ├── 7 │ │ │ ├── TComplex.cpp │ │ │ ├── TComplex.h │ │ │ └── main.cpp │ │ ├── 1&2 │ │ │ ├── output.txt │ │ │ ├── vect.cpp │ │ │ ├── vect.h │ │ │ └── 源.cpp │ │ └── readme.txt │ ├── 12 │ │ ├── 1 │ │ │ ├── cow.cpp │ │ │ ├── cow.h │ │ │ └── main.cpp │ │ └── 2 │ │ │ ├── main.cpp │ │ │ ├── string2.cpp │ │ │ └── string2.h │ └── 13 │ │ ├── 1 │ │ ├── cd.h │ │ ├── classic.h │ │ └── test.cpp │ │ ├── 2 │ │ ├── cd.h │ │ ├── classic.h │ │ └── test.cpp │ │ └── 4 │ │ ├── demo.cpp │ │ ├── port.cpp │ │ ├── port.h │ │ ├── vintage.cpp │ │ └── vintageport.h └── 《C++ Primer Plus(第6版)中文版》习题答案 │ ├── CMakeLists.txt │ ├── chapter 10 │ ├── 1 │ │ └── main.cpp │ ├── 2 │ │ └── main.cpp │ ├── 3 │ │ ├── CMakeLists.txt │ │ ├── golf.cpp │ │ ├── golf.h │ │ └── main.cpp │ ├── 4 │ │ ├── CMakeLists.txt │ │ ├── Sales.cpp │ │ ├── Sales.h │ │ └── main.cpp │ ├── 6 │ │ └── main.cpp │ ├── 7 │ │ └── main.cpp │ └── 8 │ │ └── main.cpp │ ├── chapter 11 │ ├── 1 │ │ ├── CMakeLists.txt │ │ ├── TVector.cpp │ │ ├── TVector.h │ │ ├── main.cpp │ │ └── output.txt │ ├── 2 │ │ ├── CMakeLists.txt │ │ ├── TVector.cpp │ │ ├── TVector.h │ │ └── main.cpp │ ├── 3 │ │ ├── CMakeLists.txt │ │ ├── TVector.cpp │ │ ├── TVector.h │ │ └── main.cpp │ ├── 4 │ │ ├── CMakeLists.txt │ │ ├── TTime.cpp │ │ ├── TTime.h │ │ └── main.cpp │ └── 7 │ │ ├── CMakeLists.txt │ │ ├── TComplex.cpp │ │ ├── TComplex.h │ │ └── main.cpp │ ├── chapter 12 │ ├── 1 │ │ └── main.cpp │ └── 2 │ │ ├── CMakeLists.txt │ │ ├── TString.cpp │ │ ├── TString.h │ │ └── main.cpp │ ├── chapter 13 │ ├── 1 │ │ └── main.cpp │ ├── 2 │ │ └── main.cpp │ └── 4 │ │ ├── answer │ │ └── main.cpp │ ├── chapter 14 │ ├── 1 │ │ ├── CMakeLists.txt │ │ ├── Wine.cpp │ │ ├── Wine.h │ │ └── main.cpp │ ├── 2 │ │ ├── CMakeLists.txt │ │ ├── Wine.cpp │ │ ├── Wine.h │ │ └── main.cpp │ └── 5 │ │ ├── answer │ │ └── main.cpp │ ├── chapter 16 │ ├── 1 │ │ └── main.cpp │ ├── 2 │ │ └── main.cpp │ ├── 4 │ │ └── main.cpp │ ├── 5 │ │ └── main.cpp │ ├── 7 │ │ └── main.cpp │ ├── 8 │ │ └── main.cpp │ └── 9 │ │ └── main.cpp │ ├── chapter 17 │ ├── 1 │ │ └── main.cpp │ ├── 2 │ │ └── main.cpp │ ├── 3 │ │ └── main.cpp │ ├── 4 │ │ └── main.cpp │ ├── 5 │ │ ├── all │ │ ├── main.cpp │ │ ├── mats │ │ └── pats │ └── 7 │ │ └── main.cpp │ ├── chapter 2 │ ├── 1 │ │ └── main.cpp │ ├── 2 │ │ └── main.cpp │ ├── 3 │ │ └── main.cpp │ ├── 4 │ │ └── main.cpp │ ├── 5 │ │ └── main.cpp │ ├── 6 │ │ └── main.cpp │ └── 7 │ │ └── main.cpp │ ├── chapter 3 │ ├── 1 │ │ └── main.cpp │ ├── 2 │ │ └── main.cpp │ ├── 3 │ │ └── main.cpp │ ├── 4 │ │ └── main.cpp │ ├── 5 │ │ └── main.cpp │ ├── 6 │ │ └── main.cpp │ └── 7 │ │ └── main.cpp │ ├── chapter 4 │ ├── 1 │ │ └── main.cpp │ ├── 2 │ │ └── main.cpp │ ├── 3 │ │ └── main.cpp │ ├── 4 │ │ └── main.cpp │ ├── 5 │ │ └── main.cpp │ ├── 6 │ │ └── main.cpp │ ├── 7 │ │ └── main.cpp │ ├── 8 │ │ └── main.cpp │ ├── 9 │ │ └── main.cpp │ └── 10 │ │ └── main.cpp │ ├── chapter 5 │ ├── 1 │ │ └── main.cpp │ ├── 2 │ │ └── main.cpp │ ├── 3 │ │ └── main.cpp │ ├── 4 │ │ └── main.cpp │ ├── 5 │ │ └── main.cpp │ ├── 6 │ │ └── main.cpp │ ├── 7 │ │ └── main.cpp │ ├── 8 │ │ └── main.cpp │ ├── 9 │ │ └── main.cpp │ └── 10 │ │ └── main.cpp │ ├── chapter 6 │ ├── 1 │ │ └── main.cpp │ ├── 2 │ │ └── main.cpp │ ├── 3 │ │ └── main.cpp │ ├── 4 │ │ └── main.cpp │ ├── 5 │ │ └── main.cpp │ ├── 6 │ │ └── main.cpp │ ├── 7 │ │ └── main.cpp │ ├── 8 │ │ ├── main.cpp │ │ ├── main.cpp~ │ │ └── test_(for_linux).txt │ └── 9 │ │ ├── contributor_(for_linux).txt │ │ └── main.cpp │ ├── chapter 7 │ ├── 1 │ │ ├── main.cpp │ │ └── main.cpp~ │ ├── 2 │ │ └── main.cpp │ ├── 3 │ │ └── main.cpp │ ├── 4 │ │ └── main.cpp │ ├── 5 │ │ └── main.cpp │ ├── 6 │ │ └── main.cpp │ ├── 7 │ │ └── main.cpp │ ├── 8 │ │ ├── CMakeLists.txt │ │ ├── a │ │ │ └── main.cpp │ │ └── b │ │ │ └── main.cpp │ ├── 9 │ │ ├── CMakeLists.txt │ │ └── main.cpp │ └── 10 │ │ └── main.cpp │ ├── chapter 8 │ ├── 1 │ │ └── main.cpp │ ├── 2 │ │ └── main.cpp │ ├── 3 │ │ └── main.cpp │ ├── 4 │ │ └── main.cpp │ ├── 5 │ │ └── main.cpp │ ├── 6 │ │ └── main.cpp │ └── 7 │ │ └── main.cpp │ ├── chapter 9 │ ├── 1 │ │ ├── CMakeLists.txt │ │ ├── golf.cpp │ │ ├── golf.h │ │ └── main.cpp │ ├── 2 │ │ └── main.cpp │ ├── 3 │ │ └── main.cpp │ └── 4 │ │ ├── CMakeLists.txt │ │ ├── Sales.cpp │ │ ├── Sales.h │ │ └── main.cpp │ └── readme └── imooc_code ├── data_structure ├── List │ ├── Coordinate.cpp │ ├── Coordinate.h │ ├── List.cpp │ ├── List.h │ ├── demo.cpp │ └── 通讯录 │ │ ├── List.h │ │ ├── Node.h │ │ ├── Person.h │ │ ├── demo.cpp │ │ ├── list.cpp │ │ ├── node.cpp │ │ └── person.cpp ├── Map │ ├── CMap.cpp │ ├── CMap.h │ ├── Edge.h │ ├── Node.cpp │ ├── Node.h │ ├── demo.cpp │ └── edge.cpp ├── Queue │ ├── Myqueue.h │ ├── customer.cpp │ ├── customer.h │ ├── demo.cpp │ ├── myqueue.cpp │ └── 数组存储的线性表.cpp ├── Stack │ ├── MyStack.h │ ├── demo.cpp │ ├── demo2.cpp │ ├── demo3.cpp │ └── demo4.cpp ├── Tree(List) │ ├── Node.cpp │ ├── Node.h │ ├── Tree.cpp │ ├── Tree.h │ └── demo.cpp ├── Tree │ ├── Tree.h │ ├── demo.cpp │ └── tree.cpp └── chain_list │ ├── List.h │ ├── demo.cpp │ ├── list.cpp │ ├── node.cpp │ └── node.h └── mazecode ├── MyMazeMap.cpp ├── MyMazeMap.h ├── MyMazer.cpp ├── MyMazer.h ├── main.cpp └── readme.txt /README.md: -------------------------------------------------------------------------------- 1 | ## 个人C++入门路线 2 | 3 | ### 第一阶段: C++语法学习 4 | 5 | [慕课网 C++远征系列]( 6 | https://www.imooc.com/course/list?c=cplusplus) 7 | 8 | [迷宫代码](https://github.com/Superone77/Cpp-basic-learning/tree/master/imooc_code/mazecode) 9 | 10 | C++ Primer Plus 第6版 中文版(课后习题基本刷完) 11 | 12 | [习题参考答案](https://github.com/Superone77/Cpp-basic-learning/tree/master/cpp_primer_plus_code/%E3%80%8AC%2B%2B%20Primer%20Plus%EF%BC%88%E7%AC%AC6%E7%89%88%EF%BC%89%E4%B8%AD%E6%96%87%E7%89%88%E3%80%8B%E4%B9%A0%E9%A2%98%E7%AD%94%E6%A1%88) 13 | 14 | [个人答案](https://github.com/Superone77/Cpp-basic-learning/tree/master/cpp_primer_plus_code/myCode) 15 | 16 | ### 第二阶段: C++实现常见数据结构 17 | 18 | [慕课网 数据结构探险系列]( 19 | https://www.imooc.com/course/list?c=cplusplus) 20 | 21 | [课程代码库](https://github.com/Superone77/Cpp-basic-learning/tree/master/imooc_code/data_structure) 22 | 23 | [清华大学 邓俊辉 数据结构与算法]( 24 | https://www.bilibili.com/video/av49361421/) 25 | 26 | [课程代码库]( 27 | http://dsa.cs.tsinghua.edu.cn/~deng/ds/src_link/index.htm) 28 | 29 | ### 第三阶段: 小项目实战 30 | 31 | 做了一个仓库AGV路径规划与避障的接口系统,接收上位调度系统的指令,根据指令进行路径规划和避障。 32 | 33 | 数据结构用到了**Vector, Map, Queue**。 34 | 35 | 详见 36 | 37 | [基于dijkstra算法的AGV路径规划](https://github.com/Superone77/AGV_dijkstra/tree/master) 38 | 39 | 40 | 41 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/myCode/10/1/bank.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include"bank.h" 4 | 5 | using namespace std; 6 | 7 | bank::bank(string name, string number, unsigned money) 8 | { 9 | cout << "bank()" << endl; 10 | m_name = name; 11 | m_number = number; 12 | m_money = money; 13 | } 14 | 15 | bank::~bank() 16 | { 17 | cout << "~bank()" << endl; 18 | } 19 | 20 | void bank::showName() 21 | { 22 | cout << m_name << endl; 23 | } 24 | 25 | void bank::showNumber() 26 | { 27 | cout << m_number << endl; 28 | } 29 | 30 | void bank::showMoney() 31 | { 32 | cout << m_money << endl; 33 | } 34 | 35 | void bank::increaseMoney(unsigned amount) 36 | { 37 | m_money = m_money + amount; 38 | } 39 | 40 | void bank::decreaseMoney(unsigned amount) 41 | { 42 | m_money = m_money - amount; 43 | } -------------------------------------------------------------------------------- /cpp_primer_plus_code/myCode/10/1/bank.h: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | class bank 7 | { 8 | public: 9 | bank(string name,string number,unsigned money); 10 | ~bank(); 11 | void showName(); 12 | void showNumber(); 13 | void showMoney(); 14 | void increaseMoney(unsigned amount); 15 | void decreaseMoney(unsigned amount); 16 | private: 17 | string m_name; 18 | string m_number; 19 | unsigned m_money; 20 | }; 21 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/myCode/10/1/源.cpp: -------------------------------------------------------------------------------- 1 | #include"bank.h" 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | int main() 9 | { 10 | bank fuck("superman", "DE12345", 200); 11 | fuck.showName(); 12 | fuck.showNumber(); 13 | fuck.showMoney(); 14 | 15 | fuck.increaseMoney(2); 16 | fuck.showMoney(); 17 | fuck.decreaseMoney(8); 18 | fuck.showMoney(); 19 | 20 | system("pause"); 21 | return 0; 22 | 23 | } -------------------------------------------------------------------------------- /cpp_primer_plus_code/myCode/10/2/main.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Superone77/Cpp-basic-learning/82f8f452d06ba09d4636e19769c9d072b576ece3/cpp_primer_plus_code/myCode/10/2/main.cpp -------------------------------------------------------------------------------- /cpp_primer_plus_code/myCode/10/3/golf.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Superone77/Cpp-basic-learning/82f8f452d06ba09d4636e19769c9d072b576ece3/cpp_primer_plus_code/myCode/10/3/golf.cpp -------------------------------------------------------------------------------- /cpp_primer_plus_code/myCode/10/3/golf.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | class golf 4 | { 5 | public: 6 | golf(const char*name = "", int hc = 0); 7 | int setgolf(void); 8 | void sethandicap(int hc); 9 | void showgolf(void) const; 10 | private: 11 | static const int Len = 40; 12 | char fullname[Len]; 13 | int handicap; 14 | }; -------------------------------------------------------------------------------- /cpp_primer_plus_code/myCode/10/3/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include"golf.h" 4 | #include 5 | #pragma warning(disable:4996) 6 | 7 | using namespace std; 8 | 9 | int main() 10 | { 11 | const unsigned k_size = 4; 12 | golf golfers[k_size]; 13 | unsigned numGolfers = 0; 14 | while (numGolfers < k_size&&golfers[numGolfers].setgolf()) 15 | { 16 | ++numGolfers; 17 | } 18 | for (unsigned i = 0; i < numGolfers; ++i) 19 | { 20 | golfers[i].showgolf(); 21 | cout << endl; 22 | } 23 | 24 | cout << endl; 25 | system("pause"); 26 | return 0; 27 | } -------------------------------------------------------------------------------- /cpp_primer_plus_code/myCode/10/4/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include"sale.h" 4 | 5 | using namespace std; 6 | 7 | int main(void) 8 | { 9 | using namespace SALES; 10 | 11 | Sales salesBook; 12 | salesBook.showSales(); 13 | 14 | Sales salesPen; 15 | salesPen.showSales(); 16 | 17 | cout << endl; 18 | system("pause"); 19 | return 0; 20 | 21 | } -------------------------------------------------------------------------------- /cpp_primer_plus_code/myCode/10/4/sale.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Superone77/Cpp-basic-learning/82f8f452d06ba09d4636e19769c9d072b576ece3/cpp_primer_plus_code/myCode/10/4/sale.cpp -------------------------------------------------------------------------------- /cpp_primer_plus_code/myCode/10/4/sale.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | namespace SALES 4 | { 5 | class Sales 6 | { 7 | private: 8 | static const int QUARTERS = 4; 9 | double sales[QUARTERS]; 10 | double size; 11 | double average; 12 | double max; 13 | double min; 14 | double calcAverage(void) const; 15 | double calcMax(void) const; 16 | double calcMin(void) const; 17 | 18 | public: 19 | Sales() { setSales(); } 20 | Sales(double arr[], int n); 21 | void setSales(void); 22 | void showSales(void) const; 23 | }; 24 | } 25 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/myCode/10/6/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include"move.h" 4 | 5 | using namespace std; 6 | 7 | int main(void) 8 | { 9 | 10 | 11 | Move fuck2(1,1); 12 | fuck2.showmove(); 13 | 14 | Move fuck3(1, 1); 15 | fuck3.add(fuck2).showmove(); 16 | fuck3.showmove(); 17 | fuck3.reset(); 18 | fuck3.showmove(); 19 | 20 | cout << endl; 21 | system("pause"); 22 | return 0; 23 | } -------------------------------------------------------------------------------- /cpp_primer_plus_code/myCode/10/6/move.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include"move.h" 3 | 4 | using namespace std; 5 | 6 | Move::Move(double a , double b) 7 | { 8 | x = a; 9 | y = b; 10 | } 11 | void 12 | Move::showmove(void) const 13 | { 14 | cout << x << endl; 15 | cout << y << endl; 16 | } 17 | 18 | Move Move::add(const Move&m) const 19 | { 20 | return (Move(m.x + x, m.y + y)); 21 | } 22 | void 23 | Move::reset(double a , double b) 24 | { 25 | x = a; 26 | y = b; 27 | } 28 | 29 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/myCode/10/6/move.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | class Move 4 | { 5 | private: 6 | double x; 7 | double y; 8 | public: 9 | Move(double a = 0, double b = 0); 10 | void showmove(void) const; 11 | Move add(const Move&m) const; 12 | void reset(double a = 0, double b = 0); 13 | 14 | }; 15 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/myCode/10/7/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include"plorg.h" 5 | 6 | using namespace std; 7 | 8 | int main(void) 9 | { 10 | 11 | 12 | plorg fuck2("abc", 19); 13 | fuck2.getplorg(); 14 | fuck2.setname("abcde"); 15 | fuck2.setci(12); 16 | fuck2.getplorg(); 17 | fuck2.setname("aaaaabbbbbcccccdddddeeee"); 18 | fuck2.getplorg(); 19 | 20 | system("pause"); 21 | return 0; 22 | } -------------------------------------------------------------------------------- /cpp_primer_plus_code/myCode/10/7/plorg.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include"plorg.h" 4 | 5 | using namespace std; 6 | 7 | plorg::plorg(string name, int ci) 8 | { 9 | int limit = 19; 10 | if (name.size() > limit) { 11 | m_name=name.substr(0, limit); 12 | } 13 | else 14 | m_name = name; 15 | 16 | m_ci = ci; 17 | } 18 | 19 | void plorg::setname(string name) 20 | { 21 | int limit = 19; 22 | if (name.size() > limit) { 23 | m_name = name.substr(0, limit); 24 | } 25 | else 26 | m_name = name; 27 | } 28 | void plorg::setci(int ci) 29 | { 30 | m_ci = ci; 31 | } 32 | void plorg::getplorg() 33 | { 34 | cout << "name is " << m_name << endl; 35 | cout << "CI is " << m_ci << endl; 36 | } -------------------------------------------------------------------------------- /cpp_primer_plus_code/myCode/10/7/plorg.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | class plorg 8 | { 9 | public: 10 | plorg(string name = "Plorga", int ci = 50); 11 | void setname(string name); 12 | void setci(int ci); 13 | void getplorg(); 14 | private: 15 | string m_name; 16 | int m_ci; 17 | }; -------------------------------------------------------------------------------- /cpp_primer_plus_code/myCode/11/1&2/output.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Superone77/Cpp-basic-learning/82f8f452d06ba09d4636e19769c9d072b576ece3/cpp_primer_plus_code/myCode/11/1&2/output.txt -------------------------------------------------------------------------------- /cpp_primer_plus_code/myCode/11/1&2/vect.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Superone77/Cpp-basic-learning/82f8f452d06ba09d4636e19769c9d072b576ece3/cpp_primer_plus_code/myCode/11/1&2/vect.cpp -------------------------------------------------------------------------------- /cpp_primer_plus_code/myCode/11/1&2/vect.h: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Superone77/Cpp-basic-learning/82f8f452d06ba09d4636e19769c9d072b576ece3/cpp_primer_plus_code/myCode/11/1&2/vect.h -------------------------------------------------------------------------------- /cpp_primer_plus_code/myCode/11/1&2/源.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Superone77/Cpp-basic-learning/82f8f452d06ba09d4636e19769c9d072b576ece3/cpp_primer_plus_code/myCode/11/1&2/源.cpp -------------------------------------------------------------------------------- /cpp_primer_plus_code/myCode/11/3/vect.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Superone77/Cpp-basic-learning/82f8f452d06ba09d4636e19769c9d072b576ece3/cpp_primer_plus_code/myCode/11/3/vect.cpp -------------------------------------------------------------------------------- /cpp_primer_plus_code/myCode/11/3/vect.h: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Superone77/Cpp-basic-learning/82f8f452d06ba09d4636e19769c9d072b576ece3/cpp_primer_plus_code/myCode/11/3/vect.h -------------------------------------------------------------------------------- /cpp_primer_plus_code/myCode/11/3/源.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Superone77/Cpp-basic-learning/82f8f452d06ba09d4636e19769c9d072b576ece3/cpp_primer_plus_code/myCode/11/3/源.cpp -------------------------------------------------------------------------------- /cpp_primer_plus_code/myCode/11/4/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include"time.h" 3 | #include 4 | 5 | int main() 6 | { 7 | using std::cout; 8 | using std::endl; 9 | 10 | Time aida(3.35); 11 | Time tosca(2, 48); 12 | Time temp; 13 | 14 | cout << "Aida and Tosca:\n"; 15 | cout << aida << ": " << tosca << endl; 16 | temp = aida + tosca; 17 | cout << "Aida+Tosca: " << temp << endl; 18 | temp = aida * 1.17; 19 | cout << "Aida*1.17: " << temp << endl; 20 | cout << "10.0*Tosca: " << 10.0*tosca << endl; 21 | 22 | system("pause"); 23 | return 0; 24 | } -------------------------------------------------------------------------------- /cpp_primer_plus_code/myCode/11/4/time.cpp: -------------------------------------------------------------------------------- 1 | #include "time.h" 2 | 3 | Time::Time() 4 | { 5 | hours = minutes == 0; 6 | } 7 | Time::Time(int h, int m ) 8 | { 9 | hours = h; 10 | minutes = m; 11 | } 12 | void 13 | Time::AddMin(int m) 14 | { 15 | minutes += m; 16 | hours += minutes / 60; 17 | minutes %= 60; 18 | } 19 | void 20 | Time::AddNr(int h) 21 | { 22 | hours += h; 23 | } 24 | void 25 | Time::Reset(int h, int m) 26 | { 27 | hours = h; 28 | minutes = m; 29 | } 30 | Time 31 | operator+(const Time &a, const Time &b) 32 | { 33 | Time sum; 34 | sum.minutes = a.minutes + b.minutes; 35 | sum.hours = a.hours + b.hours + sum.minutes / 60; 36 | sum.minutes %= 60; 37 | return sum; 38 | } 39 | Time 40 | operator-(const Time &a, const Time &b) 41 | { 42 | Time diff; 43 | int tot1, tot2; 44 | tot1 = a.minutes + 60 * a.hours; 45 | tot2 = b.minutes + 60 * b.hours; 46 | diff.minutes = (tot1 - tot2) % 60; 47 | diff.minutes = (tot1 - tot2) / 60; 48 | return diff; 49 | } 50 | 51 | Time 52 | operator*(double m, const Time &t) 53 | { 54 | Time result; 55 | long totalminutes = t.hours * m * 60 + t.minutes * m; 56 | result.hours = totalminutes / 60; 57 | result.minutes = totalminutes % 60; 58 | return result; 59 | } 60 | 61 | Time 62 | operator*(const Time &t, double m) 63 | { 64 | Time result; 65 | long totalminutes = t.hours * m * 60 + t.minutes * m; 66 | result.hours = totalminutes / 60; 67 | result.minutes = totalminutes % 60; 68 | return result; 69 | } 70 | 71 | 72 | std::ostream & operator<<(std::ostream &os, const Time &t) 73 | { 74 | os << t.hours << " hours, " << t.minutes << " minutes"; 75 | return os; 76 | } -------------------------------------------------------------------------------- /cpp_primer_plus_code/myCode/11/4/time.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | 5 | using namespace std; 6 | 7 | class Time 8 | { 9 | private: 10 | int hours; 11 | int minutes; 12 | 13 | public: 14 | Time(); 15 | Time(int h, int m = 0); 16 | void AddMin(int m); 17 | void AddNr(int h); 18 | void Reset(int h = 0, int m = 0); 19 | friend Time operator+(const Time &a, const Time &b); 20 | friend Time operator-(const Time &a, const Time &b); 21 | friend Time operator*(double m, const Time &t); 22 | friend Time operator*(const Time &t,double m); 23 | friend std::ostream & operator<<(std::ostream &os, const Time &t); 24 | }; -------------------------------------------------------------------------------- /cpp_primer_plus_code/myCode/11/5/stonewt.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "stonewt.h" 3 | 4 | namespace n_stonewt 5 | { 6 | Stonewt::Stonewt(double g, Mode mode) 7 | { 8 | if (mode = GRAD) 9 | { 10 | m_mode = GRAD; 11 | m_g = g; 12 | m_kg = 0.0; 13 | } 14 | else { 15 | m_mode = KG; 16 | m_kg = g; 17 | m_g = 0.0; 18 | } 19 | 20 | } 21 | Stonewt::Stonewt(int kg, double g) 22 | { 23 | m_mode = MIXING; 24 | m_left = g / kg_g; 25 | m_kg = kg + m_left; 26 | m_g = (int)g % kg_g; 27 | } 28 | 29 | Stonewt::~Stonewt() 30 | { 31 | 32 | } 33 | 34 | Stonewt 35 | Stonewt::operator+ (const Stonewt& stonewt) const 36 | { 37 | Stonewt result; 38 | result.m_kg = m_kg + stonewt.m_kg; 39 | result.m_g = m_g + stonewt.m_g; 40 | result.m_left = result.m_g / kg_g; 41 | result.m_kg += result.m_left; 42 | result.m_g = (int)result.m_g%kg_g; 43 | 44 | return result; 45 | 46 | } 47 | Stonewt 48 | Stonewt::operator- (const Stonewt& stonewt) const 49 | { 50 | Stonewt result; 51 | double x1, x2; 52 | x1 = m_kg * kg_g + m_g; 53 | x2 = stonewt.m_kg*kg_g + stonewt.m_g; 54 | result.m_g = x1 - x2; 55 | result.m_kg = result.m_g / kg_g; 56 | result.m_g = (int)result.m_g%kg_g; 57 | return result; 58 | } 59 | Stonewt 60 | Stonewt::operator* (const double m) const 61 | { 62 | Stonewt result; 63 | result.m_g = m_g * m; 64 | result.m_kg = result.m_g / kg_g + m_kg * m; 65 | result.m_g = (int)result.m_g%kg_g; 66 | return result; 67 | } 68 | 69 | ostream &operator<<(ostream &os, const Stonewt stonewt) 70 | { 71 | if (stonewt.m_mode == Stonewt::GRAD) { 72 | os << stonewt.m_g << " GRAD" ; 73 | } 74 | else if (stonewt.m_mode == Stonewt::KG) { 75 | os << stonewt.m_kg << " KG" ; 76 | } 77 | else { 78 | os << stonewt.m_kg << " KG " < 3 | 4 | using namespace std; 5 | namespace n_stonewt 6 | { 7 | 8 | class Stonewt 9 | { 10 | public: 11 | enum Mode { GRAD, KG, MIXING }; 12 | public: 13 | const int kg_g = 1000; 14 | double m_g; 15 | double m_left; 16 | double m_kg; 17 | Mode m_mode; 18 | public: 19 | Stonewt(double g,Mode mode=KG); 20 | Stonewt(int kg=0, double g=0); 21 | ~Stonewt(); 22 | 23 | Stonewt operator+ (const Stonewt& stonewt) const; 24 | Stonewt operator- (const Stonewt& stonewt) const; 25 | Stonewt operator* (const double m) const; 26 | 27 | friend ostream &operator<<(ostream &os, const Stonewt stonewt); 28 | 29 | 30 | 31 | }; 32 | } 33 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/myCode/11/5/源.cpp: -------------------------------------------------------------------------------- 1 | //stonewt test 2 | 3 | #include 4 | #include"stonewt.h" 5 | #include 6 | 7 | using namespace std; 8 | using namespace n_stonewt; 9 | 10 | int main() 11 | { 12 | Stonewt fuck1(2.0, Stonewt::GRAD); 13 | Stonewt fuck2(3.0); 14 | Stonewt fuck3(1, 2.0); 15 | 16 | cout << fuck1+fuck2 << endl << fuck2-fuck3 << endl << fuck3*3.0 << endl; 17 | system("pause"); 18 | 19 | return 0; 20 | 21 | } -------------------------------------------------------------------------------- /cpp_primer_plus_code/myCode/11/7/TComplex.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include "TComplex.h" 4 | 5 | 6 | namespace n_complex 7 | { 8 | using std::cout; 9 | using std::ostream; 10 | using std::numeric_limits; 11 | using std::streamsize; 12 | 13 | // ==================================== 14 | // 辅助函数 15 | // ==================================== 16 | 17 | // ==================================== 18 | // 成员函数 19 | // ==================================== 20 | 21 | TComplex::TComplex (double real, double imaginary) 22 | { 23 | m_real = real; 24 | m_imaginary = imaginary; 25 | } 26 | 27 | // ==================================== 28 | // 重载运算符 29 | // ==================================== 30 | 31 | ostream& 32 | operator<< (ostream& os, const TComplex& coplx) 33 | { 34 | os << '(' << coplx.m_real << ", " << coplx.m_imaginary << "i)"; 35 | return (os); 36 | } 37 | 38 | istream& 39 | operator>> (istream& is, TComplex& coplx) 40 | { 41 | cout << "real: "; 42 | is >> coplx.m_real; 43 | if (!is) { 44 | is.ignore(numeric_limits::max(), '\n'); // 清空输入缓冲区内容 45 | return (is); 46 | } 47 | 48 | cout << "imaginary: "; 49 | is >> coplx.m_imaginary; 50 | is.ignore(numeric_limits::max(), '\n'); // 清空输入缓冲区内容 51 | return (is); 52 | } 53 | 54 | TComplex 55 | operator~ (const TComplex& coplx) 56 | { 57 | return (TComplex(coplx.m_real, -coplx.m_imaginary)); 58 | } 59 | 60 | TComplex 61 | operator+ (const TComplex& lvalue, const TComplex& rvalue) 62 | { 63 | return (TComplex(lvalue.m_real + rvalue.m_real, lvalue.m_imaginary + rvalue.m_imaginary)); 64 | } 65 | 66 | TComplex 67 | operator- (const TComplex& lvalue, const TComplex& rvalue) 68 | { 69 | return (TComplex(lvalue.m_real - rvalue.m_real, lvalue.m_imaginary - rvalue.m_imaginary)); 70 | } 71 | 72 | TComplex 73 | operator* (const TComplex& lvalue, const TComplex& rvalue) 74 | { 75 | return (TComplex( lvalue.m_real * rvalue.m_real - lvalue.m_imaginary * rvalue.m_imaginary, 76 | lvalue.m_real * rvalue.m_imaginary + lvalue.m_imaginary * rvalue.m_real )); 77 | } 78 | 79 | TComplex 80 | operator* (double n, const TComplex& coplx) 81 | { 82 | return (TComplex(n*coplx.m_real, n*coplx.m_imaginary)); 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/myCode/11/7/TComplex.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | 5 | namespace n_complex 6 | { 7 | using std::ostream; 8 | using std::istream; 9 | 10 | class TComplex 11 | { 12 | public: 13 | explicit TComplex (double real = 0, double imaginary = 0); 14 | 15 | friend ostream& operator<< (ostream& os, const TComplex& coplx); 16 | friend istream& operator>> (istream& is, TComplex& coplx); 17 | friend TComplex operator~ (const TComplex& coplx); 18 | friend TComplex operator+ (const TComplex& lvalue, const TComplex& rvalue); 19 | friend TComplex operator- (const TComplex& lvalue, const TComplex& rvalue); 20 | friend TComplex operator* (const TComplex& lvalue, const TComplex& rvalue); 21 | friend TComplex operator* (double n, const TComplex& coplx); 22 | 23 | private: 24 | double m_real; 25 | double m_imaginary; 26 | }; 27 | } 28 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/myCode/11/7/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "TComplex.h" 3 | 4 | using namespace std; 5 | using namespace n_complex; 6 | 7 | int main() 8 | { 9 | TComplex a(3.0, 4.0); // initialize to (3,4i) Programming Exercises 10 | TComplex c; 11 | cout << "Enter a complex number (q to quit):\n"; 12 | while (cin >> c) 13 | { 14 | cout << "c is " << c << '\n'; 15 | cout << "complex conjugate is " << ~c << '\n'; 16 | cout << "a is " << a << "\n"; 17 | cout << "a + c is " << a + c << '\n'; 18 | cout << "a - c is " << a - c << '\n'; 19 | cout << "a * c is " << a * c << '\n'; 20 | cout << "2 * c is " << 2 * c << '\n'; 21 | cout << "Enter a complex number (q to quit):\n"; 22 | } 23 | cout << "Done!\n"; 24 | 25 | return 0; 26 | } 27 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/myCode/11/readme.txt: -------------------------------------------------------------------------------- 1 | 类的使用——友元函数&重载运算符 2 | 相关练习 -------------------------------------------------------------------------------- /cpp_primer_plus_code/myCode/12/1/cow.cpp: -------------------------------------------------------------------------------- 1 | 2 | #pragma warning (disable: 4996) 3 | #include 4 | #include 5 | #include "cow.h" 6 | using namespace std; 7 | 8 | Cow::Cow() 9 | { 10 | strcpy(name, "/0"); 11 | hobby = new char[1]; 12 | hobby[0] = '\0'; 13 | weight = 0.0; 14 | } 15 | Cow::Cow(const char * nm, const char * ho, double wt) 16 | { 17 | strcpy(name, nm); 18 | int len = strlen(ho); 19 | hobby = new char[len + 1]; 20 | strcpy(hobby, ho); 21 | weight = wt; 22 | } 23 | Cow::Cow(const Cow &c) 24 | { 25 | strcpy(name,c.name); 26 | int len = strlen(c.hobby); 27 | hobby = new char[len + 1]; 28 | weight = c.weight; 29 | strcpy(hobby, c.hobby); 30 | } 31 | Cow::~Cow() 32 | { 33 | delete[] hobby; 34 | } 35 | Cow & Cow::operator = (const Cow &c) 36 | { 37 | if (this == &c) 38 | return *this; 39 | delete[] hobby; 40 | int len = strlen(c.hobby); 41 | hobby = new char[len + 1]; 42 | strcpy(hobby, c.hobby); 43 | strcpy(name, c.name); 44 | weight = c.weight; 45 | return *this; 46 | } 47 | void Cow::ShowCow() const 48 | { 49 | cout <<"name: "<< name << endl; 50 | cout << "hobby: " << hobby << endl; 51 | cout << "weight: " << weight << endl; 52 | 53 | } -------------------------------------------------------------------------------- /cpp_primer_plus_code/myCode/12/1/cow.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | class Cow { 4 | char name[20]; 5 | char *hobby; 6 | double weight; 7 | public: 8 | Cow(); 9 | Cow(const char * nm, const char * ho, double wt); 10 | Cow(const Cow &c); 11 | ~Cow(); 12 | Cow &operator = (const Cow &c); 13 | void ShowCow() const; 14 | }; 15 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/myCode/12/1/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include"cow.h" 4 | 5 | using namespace std; 6 | 7 | int main() 8 | { 9 | char cowName[20]; 10 | char *cowHobby = new char[20]; 11 | double cowWeight; 12 | cout << "Enter the name: "; 13 | cin >> cowName; 14 | cout << "Enter the hobby: "; 15 | cin >> cowHobby; 16 | cout << "Enter the weight: "; 17 | cin >> cowWeight; 18 | Cow cow1; 19 | Cow cow2(cowName, cowHobby, cowWeight); 20 | Cow cow3 = cow2; 21 | cow1.ShowCow(); 22 | cow2.ShowCow(); 23 | cow3.ShowCow(); 24 | 25 | system("pause"); 26 | return 0; 27 | 28 | 29 | } -------------------------------------------------------------------------------- /cpp_primer_plus_code/myCode/12/2/main.cpp: -------------------------------------------------------------------------------- 1 | #pragma warning (disable: 4996) 2 | #include 3 | #include "string2.h" 4 | 5 | using namespace std; 6 | 7 | int main() 8 | { 9 | String s1(" and I am a C++ student."); 10 | String s2 = "Please enter your name: "; 11 | String s3; 12 | cout << s2; 13 | // overloaded << operator 14 | cin >> s3; 15 | // overloaded >> operator 16 | s2 = "My name is " + s3; 17 | // overloaded =, + operators 18 | cout << s2 << ".\n"; 19 | s2 = s2 + s1; 20 | s2.Stringup(); 21 | // converts string to uppercase 22 | cout << "The string\n" << s2 << "\ncontains " << s2.countchar('A') 23 | << " 'A' characters in it.\n"; 24 | s1 = "red"; 25 | // tstring(const char *), 26 | // then tstring & operator=(const string&) 27 | String rgb[3] = { String(s1), String("green"), String("blue") }; 28 | cout << "enter the name of a primary color for mixing light: "; 29 | String ans; 30 | bool success = false; 31 | while (cin >> ans) 32 | { 33 | ans.Stringlow(); 34 | // converts string to lowercase 35 | for (int i = 0; i < 3; i++) 36 | { 37 | if (ans == rgb[i]) // overloaded == operator 38 | { 39 | cout << "That's right!\n"; 40 | success = true; 41 | break; 42 | } 43 | } 44 | if (success) 45 | break; 46 | else 47 | cout << "Try again!\n"; 48 | } 49 | cout << "Bye\n"; 50 | return 0; 51 | } 52 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/myCode/12/2/string2.h: -------------------------------------------------------------------------------- 1 | 2 | // string1.h -- fixed and augmented string class definition 3 | 4 | #ifndef STRING1_H_ 5 | #define STRING1_H_ 6 | #include 7 | using std::ostream; 8 | using std::istream; 9 | 10 | class String 11 | { 12 | private: 13 | char * str; // pointer to string 14 | int len; // length of string 15 | static int num_strings; // number of objects 16 | static const int CINLIM = 80; // cin input limit 17 | public: 18 | // constructors and other methods 19 | String(const char * s); // constructor 20 | String(); // default constructor 21 | String(const String &); // copy constructor 22 | ~String(); // destructor 23 | int length() const { return len; } 24 | // overloaded operator methods 25 | String & operator=(const String &); 26 | String & operator=(const char *); 27 | friend String operator+(const String &st1, const String &st2); 28 | char & operator[](int i); 29 | const char & operator[](int i) const; 30 | // overloaded operator friends 31 | friend bool operator<(const String &st, const String &st2); 32 | friend bool operator>(const String &st1, const String &st2); 33 | friend bool operator==(const String &st, const String &st2); 34 | friend ostream & operator<<(ostream & os, const String & st); 35 | friend istream & operator>>(istream & is, String & st); 36 | // static function 37 | static int HowMany(); 38 | void Stringlow(); 39 | void Stringup(); 40 | int countchar(char c); 41 | }; 42 | #endif 43 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/myCode/13/1/cd.h: -------------------------------------------------------------------------------- 1 | //base class 2 | #pragma once 3 | #include 4 | #include 5 | #pragma warning (disable: 4996) 6 | 7 | using namespace std; 8 | 9 | class Cd { 10 | private: 11 | char performers[50]; 12 | char label[20]; 13 | int selections; 14 | double playtime; 15 | 16 | public: 17 | explicit Cd(const char * s1 = " ", const char * s2=" ", int n=0, double x=0.0); 18 | //Cd(const Cd &d); 19 | Cd(); 20 | virtual ~Cd(){} 21 | virtual void Report() const; 22 | //Cd & operator =(const Cd & d); 23 | }; 24 | 25 | static void 26 | copyChar(char *p_recevier, const char * p_input, unsigned charSize) 27 | { 28 | unsigned str_len = strlen(p_input) < charSize - 1 ? strlen(p_input) : charSize - 1; 29 | strncpy(p_recevier, p_input, str_len); 30 | p_recevier[str_len] = '\0'; 31 | } 32 | 33 | Cd::Cd(const char * s1, const char * s2, int n , double x) 34 | :selections(n), playtime(x) 35 | { 36 | copyChar(performers, s1, 50); 37 | copyChar(label, s2, 20); 38 | } 39 | 40 | void 41 | Cd::Report() const 42 | { 43 | cout << performers << ", " << label << ", " << selections << flush; 44 | } 45 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/myCode/13/1/classic.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "cd.h" 4 | 5 | 6 | class Classic : public Cd 7 | { 8 | private: 9 | static const unsigned mk_size = 64; 10 | 11 | private: 12 | char m_songs[mk_size]; 13 | 14 | public: 15 | Classic(const char *songs_list = "", const char * s1="", const char * s2 = "", int n = 0, double x = 0.0); 16 | virtual void Report() const; 17 | }; 18 | 19 | Classic::Classic(const char *songs_list, const char * s1, const char * s2, int n, double x) : Cd::Cd(s1,s2,n,x) 20 | { 21 | copyChar(m_songs, songs_list, mk_size); 22 | } 23 | 24 | void 25 | Classic::Report()const 26 | { 27 | Cd::Report(); 28 | cout << ", " << m_songs << endl; 29 | } -------------------------------------------------------------------------------- /cpp_primer_plus_code/myCode/13/1/test.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include"cd.h" 3 | #include"classic.h" 4 | #include 5 | using namespace std; 6 | void Bravo(const Cd & disk); 7 | 8 | int main() 9 | { 10 | Cd c1("Beatles", "Capitol", 14, 35.5); 11 | Classic c2 = Classic("Piano Sonata in B flat, Fantasia in e", "Alfred Brendel", "Philips", 2, 57.17); 12 | Cd *pcd = &c1; 13 | 14 | cout << "Using object directly:\n"; 15 | c1.Report(); 16 | c2.Report(); 17 | 18 | cout << "Using type cd * pointer to objects:\n"; 19 | pcd->Report(); 20 | pcd = &c2; 21 | pcd->Report(); 22 | 23 | cout << "Calling a function with a Cd reference argument:\n"; 24 | Bravo(c1); 25 | Bravo(c2); 26 | 27 | cout << "Testing assignment: "; 28 | Classic copy; 29 | copy = c2; 30 | copy.Report(); 31 | 32 | system("pause"); 33 | 34 | return 0; 35 | } 36 | 37 | void Bravo(const Cd & disk) 38 | { 39 | disk.Report(); 40 | 41 | } 42 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/myCode/13/2/cd.h: -------------------------------------------------------------------------------- 1 | //base class 2 | #pragma once 3 | #include 4 | #include 5 | #pragma warning (disable: 4996) 6 | 7 | using namespace std; 8 | 9 | class Cd { 10 | private: 11 | char *performers; 12 | char *label; 13 | int selections; 14 | double playtime; 15 | 16 | public: 17 | explicit Cd(const char * s1 = " ", const char * s2=" ", int n=0, double x=0.0); 18 | Cd(const Cd &d); 19 | Cd(); 20 | virtual ~Cd(); 21 | virtual void Report() const; 22 | Cd & operator =(const Cd & d); 23 | }; 24 | 25 | static char* 26 | copyChar(const char* p_src_txt) 27 | { 28 | unsigned str_len = strlen(p_src_txt); 29 | char * p_des_txt = new char[str_len + 1]; 30 | strcpy(p_des_txt, p_src_txt); 31 | 32 | return (p_des_txt); 33 | } 34 | 35 | Cd::Cd(const char * s1, const char * s2, int n , double x) 36 | :selections(n), playtime(x) 37 | { 38 | performers = copyChar(s1); 39 | label = copyChar(s2); 40 | } 41 | 42 | Cd::~Cd() 43 | { 44 | delete[] performers; 45 | delete[] label; 46 | } 47 | 48 | Cd::Cd(const Cd &d) 49 | :selections(d.selections), playtime(d.playtime) 50 | { 51 | performers = copyChar(d.performers); 52 | label = copyChar(d.performers); 53 | } 54 | 55 | Cd & 56 | Cd::operator=(const Cd & d) 57 | { 58 | if (&d == this) { 59 | return (*this); 60 | } 61 | 62 | delete[] performers; 63 | performers = copyChar(d.performers); 64 | 65 | delete[] label; 66 | label = copyChar(d.label); 67 | 68 | selections = d.selections; 69 | 70 | playtime = d.playtime; 71 | 72 | return (*this); 73 | } 74 | 75 | void 76 | Cd::Report() const 77 | { 78 | cout << performers << ", " << label << ", " << selections << flush; 79 | } 80 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/myCode/13/2/classic.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "cd.h" 4 | 5 | 6 | class Classic : public Cd 7 | { 8 | 9 | private: 10 | char * songs; 11 | 12 | public: 13 | explicit Classic(const char *songs_list = "", const char * s1="", const char * s2 = "", int n = 0, double x = 0.0); 14 | virtual void Report() const; 15 | virtual ~Classic(); 16 | Classic(const Classic & classic); 17 | Classic & operator=(const Classic& classic); 18 | }; 19 | 20 | Classic::Classic(const char *songs_list, const char * s1, const char * s2, int n, double x) : Cd::Cd(s1,s2,n,x) 21 | { 22 | songs = copyChar(songs_list); 23 | } 24 | 25 | Classic::Classic(const Classic& classic):Cd(classic) 26 | { 27 | songs = copyChar(classic.songs); 28 | } 29 | 30 | Classic& 31 | Classic::operator=(const Classic& classic) 32 | { 33 | if (&classic == this) 34 | { 35 | return(*this); 36 | } 37 | Cd::operator=(classic); 38 | 39 | delete[]songs; 40 | songs = copyChar(classic.songs); 41 | } 42 | 43 | void 44 | Classic::Report()const 45 | { 46 | Cd::Report(); 47 | cout << ", " << songs << endl; 48 | } 49 | 50 | Classic::~Classic() 51 | { 52 | delete[] songs; 53 | } -------------------------------------------------------------------------------- /cpp_primer_plus_code/myCode/13/2/test.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include"cd.h" 3 | #include"classic.h" 4 | #include 5 | using namespace std; 6 | void Bravo(const Cd & disk); 7 | 8 | int main() 9 | { 10 | Cd c1("Beatles", "Capitol", 14, 35.5); 11 | Classic c2 = Classic("Piano Sonata in B flat, Fantasia in e", "Alfred Brendel", "Philips", 2, 57.17); 12 | Cd *pcd = &c1; 13 | 14 | cout << "Using object directly:\n"; 15 | c1.Report(); 16 | c2.Report(); 17 | 18 | cout << "Using type cd * pointer to objects:\n"; 19 | pcd->Report(); 20 | pcd = &c2; 21 | pcd->Report(); 22 | 23 | cout << "Calling a function with a Cd reference argument:\n"; 24 | Bravo(c1); 25 | Bravo(c2); 26 | 27 | cout << "Testing assignment: "; 28 | Classic copy; 29 | copy = c2; 30 | copy.Report(); 31 | 32 | system("pause"); 33 | 34 | return 0; 35 | } 36 | 37 | void Bravo(const Cd & disk) 38 | { 39 | disk.Report(); 40 | 41 | } 42 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/myCode/13/4/demo.cpp: -------------------------------------------------------------------------------- 1 | #include"port.h" 2 | #include"vintageport.h" 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | int main() 9 | { 10 | Port port1("gallo", "tawny", 20); 11 | cout << port1 << endl << endl; 12 | 13 | VintagePort vp("gallo", 24, "nice", 16); 14 | VintagePort vp2(vp); 15 | cout << vp2 << endl << endl; 16 | 17 | VintagePort vp3; 18 | vp3 = vp; 19 | cout << vp3 << endl << endl; 20 | 21 | Port* p_port; 22 | p_port = &port1; 23 | p_port->Show(); 24 | cout << endl; 25 | p_port = &vp; 26 | p_port->Show(); 27 | cout << endl; 28 | 29 | system("pause"); 30 | return 0; 31 | 32 | } -------------------------------------------------------------------------------- /cpp_primer_plus_code/myCode/13/4/port.cpp: -------------------------------------------------------------------------------- 1 | #pragma warning (disable: 4996) 2 | #include"port.h" 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | static char* 9 | cpNewStr(const char* p_src_txt) 10 | { 11 | unsigned str_len = strlen(p_src_txt); 12 | char* p_des_txt = new char[str_len + 1]; 13 | strcpy(p_des_txt, p_src_txt); 14 | 15 | return (p_des_txt); 16 | } 17 | static void 18 | cpStr(char* p_des_txt, const char* p_src_txt, unsigned des_arr_size) 19 | { 20 | unsigned str_len = strlen(p_src_txt) < des_arr_size - 1 ? strlen(p_src_txt) : des_arr_size - 1; 21 | strncpy(p_des_txt, p_src_txt, str_len); 22 | p_des_txt[str_len] = '\0'; 23 | } 24 | 25 | Port::Port(const char *br, const char*st, int b ) 26 | : brand(cpNewStr(br)), bottles(b) 27 | { 28 | 29 | for (int i = 0; i < 20; i++) 30 | style[i] = st[i]; 31 | } 32 | 33 | Port::Port(const Port & p) 34 | : brand(cpNewStr(p.brand)), bottles(p.bottles) 35 | { 36 | 37 | for (int i = 0; i < 20; i++) 38 | style[i] = p.style[i]; 39 | } 40 | 41 | Port & 42 | Port::operator=(const Port &p) 43 | { 44 | brand = cpNewStr(p.brand); 45 | for (int i = 0; i < 20; i++) 46 | style[i] = p.style[i]; 47 | bottles = p.bottles; 48 | return *this; 49 | } 50 | 51 | Port & 52 | Port::operator+=(int b) 53 | { 54 | bottles += b; 55 | return *this; 56 | } 57 | 58 | Port & 59 | Port::operator-=(int b) 60 | { 61 | bottles -= b; 62 | return *this; 63 | } 64 | 65 | void 66 | Port::Show() const 67 | { 68 | cout << endl; 69 | cout << "Brand: " << brand << endl; 70 | cout << "Kind: " << style << endl; 71 | cout << "Bottles: " << bottles << endl; 72 | } 73 | 74 | ostream & operator<<(ostream & os, const Port & p) 75 | { 76 | os << p.brand << ", " << p.style << ", " << p.bottles << endl; 77 | return os; 78 | } 79 | 80 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/myCode/13/4/port.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | using namespace std; 5 | 6 | class Port 7 | { 8 | private: 9 | char * brand; 10 | char style[20]; // i.e., tawny, ruby, vintage 11 | int bottles; 12 | public: 13 | explicit Port(const char * br = "none", const char * st = "none", int b = 0); 14 | Port(const Port & p); // copy constructor 15 | virtual ~Port() { delete[] brand; brand = NULL; } 16 | Port & operator=(const Port & p); 17 | virtual void Show() const; 18 | Port & operator+=(int b); // adds b to bottles 19 | Port & operator-=(int b); // subtracts b from bottles, if available 20 | int BottleCount() const { return bottles; } 21 | friend ostream & operator<<(ostream & os, const Port & p); 22 | }; -------------------------------------------------------------------------------- /cpp_primer_plus_code/myCode/13/4/vintage.cpp: -------------------------------------------------------------------------------- 1 | #pragma warning (disable: 4996) 2 | #include "vintageport.h" 3 | #include"port.h" 4 | 5 | using namespace std; 6 | 7 | static char* 8 | cpNewStr(const char* p_src_txt) 9 | { 10 | unsigned str_len = strlen(p_src_txt); 11 | char* p_des_txt = new char[str_len + 1]; 12 | strcpy(p_des_txt, p_src_txt); 13 | 14 | return (p_des_txt); 15 | } 16 | 17 | 18 | VintagePort::VintagePort(const char * br, int b, const char * nn, int y) 19 | :Port(br,"Vintage",b), nickname(cpNewStr(nn)), year(y) 20 | { 21 | ; 22 | } 23 | 24 | VintagePort::VintagePort(const VintagePort &vp) 25 | : Port(vp), nickname(cpNewStr(vp.nickname)), year(vp.year) 26 | { 27 | ; 28 | } 29 | 30 | void 31 | VintagePort::Show() const 32 | { 33 | Port::Show(); 34 | cout << endl; 35 | cout << "Nickname: " << nickname << endl; 36 | cout << "Year: " << year << flush; 37 | } 38 | 39 | VintagePort & 40 | VintagePort::operator=(const VintagePort & vp) 41 | { 42 | if (&vp == this) 43 | return *this; 44 | Port::operator=(vp); 45 | delete[] nickname; 46 | nickname = cpNewStr(vp.nickname); 47 | 48 | year = vp.year; 49 | return (*this); 50 | } 51 | 52 | ostream & 53 | operator<<(ostream &os, const VintagePort & vp) 54 | { 55 | os << Port(vp); 56 | cout << ", " << vp.nickname << ", " << vp.year << flush; 57 | return (os); 58 | } -------------------------------------------------------------------------------- /cpp_primer_plus_code/myCode/13/4/vintageport.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include"port.h" 3 | 4 | 5 | class VintagePort : public Port // style necessarily = "vintage" 6 | { 7 | private: 8 | char * nickname; // i.e., "The Noble" or "Old Velvet", etc. 9 | int year; // vintage year 10 | public: 11 | explicit VintagePort(const char * br = "", int b = 0, const char * nn = "", int y = 0); 12 | VintagePort(const VintagePort & vp); 13 | virtual ~VintagePort() { delete[] nickname; } 14 | VintagePort & operator=(const VintagePort & vp); 15 | virtual void Show() const; 16 | friend ostream & operator<<(ostream & os, const VintagePort & vp); 17 | }; -------------------------------------------------------------------------------- /cpp_primer_plus_code/myCode/6/1/main1.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | int main() 7 | { 8 | 9 | char ch; 10 | 11 | cout << "Please enter something with keyboard and end with @" << endl; 12 | 13 | 14 | ch = cin.get(); 15 | while (ch != '@') 16 | { 17 | if (isdigit(ch)) 18 | ch = cin.get(); 19 | else if (islower(ch)) { 20 | ch=toupper(ch); 21 | cout << ch; 22 | ch = cin.get(); 23 | } 24 | else if (isupper(ch)) { 25 | ch=tolower(ch); 26 | cout << ch; 27 | ch = cin.get(); 28 | } 29 | else { 30 | cout << ch; 31 | ch = cin.get(); 32 | } 33 | 34 | 35 | } 36 | 37 | cout << endl; 38 | 39 | 40 | return 0; 41 | } -------------------------------------------------------------------------------- /cpp_primer_plus_code/myCode/6/2/main1.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | int main() 8 | { 9 | 10 | const int ArSize = 10; 11 | double donation[ArSize]; 12 | 13 | cout << "enter maximal 10 number:" << endl; 14 | 15 | int i = 0; 16 | int average = 0; 17 | int sum = 0; 18 | while (i> donation[i]) { 19 | sum = sum + donation[i]; 20 | i++; 21 | } 22 | 23 | average = sum / i; 24 | 25 | int number = 0; 26 | 27 | for (int j = 0; j < i; j++) { 28 | if (donation[j] > average) { 29 | number++; 30 | } 31 | } 32 | 33 | cout << "average of these numbers is " << average << endl; 34 | cout << number << " number are bigger than the average."; 35 | cout << endl; 36 | 37 | system("pause"); 38 | 39 | return 0; 40 | } -------------------------------------------------------------------------------- /cpp_primer_plus_code/myCode/6/3/main1.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | int main() 7 | { 8 | cout << "Please enter one of the following choices:" << endl; 9 | cout << "c) carnivore p) pianist" << endl; 10 | cout << "t) tree g) game" << endl; 11 | 12 | char ch; 13 | 14 | cin >> ch; 15 | while (ch != 'c' && ch != 'p' && ch != 't' && ch != 'g') { 16 | cout << "Please enter a c,p,t or g:"; 17 | cin >> ch; 18 | } 19 | switch (ch) 20 | { 21 | case 'c':cout << "~-~"; break; 22 | case 'p':cout << "~-~"; break; 23 | case 't':cout << "A maple is a tree."; break; 24 | case 'g':cout << "~-~"; 25 | } 26 | 27 | cout << endl; 28 | 29 | system("pause"); 30 | 31 | return 0; 32 | } -------------------------------------------------------------------------------- /cpp_primer_plus_code/myCode/6/4/main1.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | const unsigned strsize = 64; 7 | 8 | struct bop { 9 | char fullname[strsize];//real name 10 | char title[strsize];//job title; 11 | char bopname[strsize];//secret BOP name 12 | int preference;//0=fullname,1=title,2=bopname 13 | }; 14 | 15 | int main() 16 | { 17 | 18 | const int BSize = 4; 19 | bop everybodyletsgo[BSize] = { {"Yang Yang", "chinamobile", "yangyang.gnu", 1}, 20 | {"xiao wang", "microsoft", "xiaowang", 2}, 21 | {"xiao liu", "IBM", "xiaoliu", 0}, 22 | {"xiao zhang", "Huawei", "xiaozhang",1} }; 23 | 24 | cout << "Benevolent Order of Programmers Report" << endl; 25 | cout << "a. display by name b. display by title" << endl; 26 | cout << "c. display by bopname d. display by preference" << endl; 27 | cout << "q. quit" << endl; 28 | cout << "enter your choice: "; 29 | 30 | char ch; 31 | 32 | while (cin >> ch && ch != 'q') { 33 | switch (ch) 34 | { 35 | case 'a': 36 | { 37 | for (int i = 0; i < BSize; i++) { 38 | cout << everybodyletsgo[i].fullname << endl; 39 | } 40 | cout << "Next choice: "; 41 | break; 42 | } 43 | case 'b': 44 | { 45 | for (int i = 0; i < BSize; i++) { 46 | cout << everybodyletsgo[i].title << endl; 47 | } 48 | cout << "Next choice: "; 49 | break; 50 | } 51 | case 'c': 52 | { 53 | for (int i = 0; i < BSize; i++) { 54 | cout << everybodyletsgo[i].bopname << endl; 55 | } 56 | cout << "Next choice: "; 57 | break; 58 | } 59 | case 'd': 60 | { 61 | for (int i = 0; i < BSize; i++) { 62 | 63 | if(everybodyletsgo[i].preference=0) 64 | cout << everybodyletsgo[i].fullname << endl; 65 | 66 | else if(everybodyletsgo[i].preference = 1) 67 | cout << everybodyletsgo[i].title << endl; 68 | else cout << everybodyletsgo[i].bopname << endl; 69 | 70 | } 71 | cout << "Next choice: "; 72 | break; 73 | } 74 | 75 | default: 76 | break; 77 | } 78 | } 79 | 80 | cout << "Bye!" << endl; 81 | 82 | 83 | system("pause"); 84 | 85 | return 0; 86 | } -------------------------------------------------------------------------------- /cpp_primer_plus_code/myCode/6/5/main1.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | int main() 7 | { 8 | const float taxPercent1 = 0.1; 9 | const float taxPercent2 = 0.15; 10 | const float taxPercent3 = 0.2; 11 | long income; 12 | long tax; 13 | 14 | cout << "Enter your income: "; 15 | 16 | while (cin >> income && income > 0) { 17 | if (income < 5000) { 18 | tax = 0; 19 | } 20 | else if (income < 15000 && income>5000) { 21 | tax = (income - 5000)*taxPercent1; 22 | } 23 | else if (income < 35000 && income>15000) { 24 | tax = (income - 1500)*taxPercent2 + 10000 * taxPercent1; 25 | } 26 | else tax = (income - 35000)*taxPercent3 + 20000 * taxPercent2 + 10000 * taxPercent1; 27 | cout << "your tax is " << tax << " tvarps" << endl; 28 | } 29 | 30 | cout << "Bye!" << endl; 31 | 32 | 33 | 34 | 35 | system("pause"); 36 | 37 | return 0; 38 | } -------------------------------------------------------------------------------- /cpp_primer_plus_code/myCode/6/6/main1.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | struct goodman { 8 | string name; 9 | double money; 10 | }; 11 | int main() 12 | { 13 | int num_goodman = 0; 14 | cout << "Please enter the number of the goodman: "; 15 | cin >> num_goodman; 16 | 17 | goodman* const Wuhan= new goodman [num_goodman]; 18 | for (int i = 0; i < num_goodman; i++) { 19 | cout << "Enter the name: "; 20 | cin >> Wuhan[i].name; 21 | cout << "How much has this guy give? " << endl; 22 | cin >> Wuhan[i].money; 23 | } 24 | 25 | cout << "Grand Patrons" << endl; 26 | for (int i = 0; i < num_goodman; i++) { 27 | if (Wuhan[i].money > 10000) 28 | cout << Wuhan[i].name << endl; 29 | } 30 | 31 | cout << endl; 32 | 33 | cout << "Patrons" << endl; 34 | for (int i = 0; i < num_goodman; i++) { 35 | if (Wuhan[i].money <= 10000) 36 | cout << Wuhan[i].name << endl; 37 | } 38 | 39 | 40 | system("pause"); 41 | 42 | return 0; 43 | } -------------------------------------------------------------------------------- /cpp_primer_plus_code/myCode/6/7/main1.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Superone77/Cpp-basic-learning/82f8f452d06ba09d4636e19769c9d072b576ece3/cpp_primer_plus_code/myCode/6/7/main1.cpp -------------------------------------------------------------------------------- /cpp_primer_plus_code/myCode/6/8/main1.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | struct goodman { 9 | string name; 10 | double money; 11 | }; 12 | 13 | int main() 14 | { 15 | ifstream inFile; 16 | int num_goodman = 0; 17 | inFile.open("C:\\Users\\Superone77\\Desktop\\6\\9\\donation.txt"); 18 | inFile >> num_goodman; 19 | 20 | goodman* const Wuhan = new goodman[num_goodman]; 21 | 22 | for (int i = 0; i < num_goodman; i++) { 23 | inFile.get(); 24 | getline(inFile, Wuhan[i].name); 25 | ifs >> Wuhan[i].amount; 26 | } 27 | inFile.close(); 28 | 29 | cout << "Grand Patrons" << endl; 30 | for (int i = 0; i < num_goodman; i++) { 31 | if (Wuhan[i].money > 10000) 32 | cout << Wuhan[i].name << endl; 33 | } 34 | 35 | cout << endl; 36 | 37 | cout << "Patrons" << endl; 38 | for (int i = 0; i < num_goodman; i++) { 39 | if (Wuhan[i].money <= 10000) 40 | cout << Wuhan[i].name << endl; 41 | } 42 | 43 | 44 | 45 | 46 | return 0; 47 | } -------------------------------------------------------------------------------- /cpp_primer_plus_code/myCode/6/9/donation.txt: -------------------------------------------------------------------------------- 1 | 4 2 | Sam Stone 3 | 2000 4 | Preida Flass 5 | 100500 6 | Tammy Tubbs 7 | 5000 8 | Rich Raptor 9 | 55000 -------------------------------------------------------------------------------- /cpp_primer_plus_code/myCode/6/9/main1.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | struct goodman { 9 | string name; 10 | double money; 11 | }; 12 | 13 | int main() 14 | { 15 | ifstream inFile; 16 | int num_goodman = 0; 17 | inFile.open("donation.txt"); 18 | inFile >> num_goodman; 19 | 20 | goodman* const Wuhan = new goodman[num_goodman]; 21 | 22 | for (int i = 0; i < num_goodman; i++) { 23 | inFile.get(); 24 | getline(inFile, Wuhan[i].name); 25 | inFile >> Wuhan[i].money; 26 | } 27 | inFile.close(); 28 | 29 | cout << "Grand Patrons" << endl; 30 | for (int i = 0; i < num_goodman; i++) { 31 | if (Wuhan[i].money > 10000) 32 | cout << Wuhan[i].name << endl; 33 | } 34 | 35 | cout << endl; 36 | 37 | cout << "Patrons" << endl; 38 | for (int i = 0; i < num_goodman; i++) { 39 | if (Wuhan[i].money <= 10000) 40 | cout << Wuhan[i].name << endl; 41 | } 42 | 43 | 44 | 45 | 46 | return 0; 47 | } -------------------------------------------------------------------------------- /cpp_primer_plus_code/myCode/7/1/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | float tAverage(float x, float y); 5 | 6 | int main() 7 | { 8 | using namespace std; 9 | 10 | float x = 1.0; 11 | float y = 1.0; 12 | float z; 13 | 14 | while (x != 0 && y != 0) { 15 | cout << "Enter first number:"; 16 | cin >> x; 17 | cout << "Enter second number: "; 18 | cin >> y; 19 | z = tAverage(x, y); 20 | cout << z << " is their tiaohepingjunshu!" << endl; 21 | 22 | } 23 | cout << "Done!"; 24 | cout << endl; 25 | 26 | system("pause"); 27 | return 0; 28 | } 29 | 30 | float tAverage(float x, float y) 31 | { 32 | using namespace std; 33 | float temp; 34 | temp = 2.0*x*y / (x + y); 35 | 36 | return temp; 37 | } -------------------------------------------------------------------------------- /cpp_primer_plus_code/myCode/7/2/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | int fill_array(int grade[], int limit); 4 | void show_array(const int grade[], int n); 5 | float average(const int grade[], int n); 6 | const int Size = 10; 7 | 8 | using namespace std; 9 | 10 | int main() 11 | { 12 | int grade[Size]; 13 | int i = fill_array(grade, Size); 14 | show_array(grade, i); 15 | 16 | if (i != 0) { 17 | float a = average(grade, i); 18 | 19 | cout << "the average of the grade is " << a<> temp; 41 | if (!cin) { 42 | cin.clear(); 43 | while (cin.get() != '\n') 44 | continue; 45 | cout << "Enter is finished. \n"; 46 | break; 47 | } 48 | else if (temp < 0) 49 | break; 50 | grade[i] = temp; 51 | } 52 | return i; 53 | } 54 | void show_array(const int grade[], int n) 55 | { 56 | cout << "The golfgrade are: " << endl; 57 | for (int i = 0; i < n; i++) 58 | { 59 | cout << grade[i] << ", "; 60 | } 61 | 62 | cout << endl; 63 | } 64 | float average(const int grade[], int n) 65 | { 66 | float temp; 67 | int sum = 0; 68 | for (int i = 0; i < n; i++) { 69 | sum = sum + grade[i]; 70 | } 71 | temp = 1.0*sum / n; 72 | 73 | return temp; 74 | } -------------------------------------------------------------------------------- /cpp_primer_plus_code/myCode/7/3/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | struct box 4 | { 5 | char maker[40]; 6 | float height; 7 | float width; 8 | float length; 9 | float volume; 10 | }; 11 | 12 | void build_box(box fuck); 13 | void V_box(box* pfuck); 14 | 15 | using namespace std; 16 | 17 | int main() 18 | { 19 | box fuck = { "FUCKBOX",8,12,10 }; 20 | 21 | build_box(fuck); 22 | 23 | V_box(&fuck); 24 | 25 | cout << endl; 26 | cout << "Volume of the box is " << fuck.volume << endl; 27 | 28 | system("pause"); 29 | return 0; 30 | } 31 | 32 | void build_box(box fuck) 33 | { 34 | cout << fuck.maker << " have the factors: " << endl; 35 | cout << fuck.height << ", " << fuck.width << ", " << fuck.length << endl; 36 | 37 | } 38 | void V_box(box* pfuck) 39 | { 40 | pfuck->volume = pfuck->height*pfuck->length*pfuck->width; 41 | } -------------------------------------------------------------------------------- /cpp_primer_plus_code/myCode/7/4/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | long double probability(unsigned numbers, unsigned picks); 5 | 6 | using namespace std; 7 | 8 | int main() 9 | { 10 | int x1 = 47, x2 = 27; 11 | int y1 = 5, y2 = 1; 12 | long double n1, n2; 13 | n1 = probability(x1, y1); 14 | n2 = probability(x2, y2); 15 | 16 | cout << "You have one chance in " << n1 * n2 << " of winning" << endl; 17 | 18 | cout << "Done."; 19 | cout << endl; 20 | 21 | system("pause"); 22 | return 0; 23 | } 24 | 25 | long double probability(unsigned numbers, unsigned picks) 26 | { 27 | long double fuck = 1.0; 28 | long double n; 29 | unsigned p; 30 | 31 | for (n = numbers, p = picks; p > 0; n--, p--) 32 | fuck = fuck * n / p; 33 | return fuck; 34 | } -------------------------------------------------------------------------------- /cpp_primer_plus_code/myCode/7/5/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | long fuck(int x); 5 | 6 | using namespace std; 7 | 8 | int main() 9 | { 10 | int x; 11 | cout << "Please enter number to check the program" << endl; 12 | 13 | while (cin >> x&&x>=0) { 14 | cout << "result is " << fuck(x) << endl; 15 | } 16 | 17 | cout << "Done."; 18 | cout << endl; 19 | 20 | system("pause"); 21 | return 0; 22 | } 23 | 24 | long fuck(int x) 25 | { 26 | long temp; 27 | if (x != 0) 28 | temp = x * fuck(x - 1); 29 | else 30 | temp = 1; 31 | 32 | 33 | return temp; 34 | } -------------------------------------------------------------------------------- /cpp_primer_plus_code/myCode/7/6/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int Fill_array(double ar[], int limit); 5 | void Show_array(double ar[], int size); 6 | void Reverse_array(double ar[], int size); 7 | const int k = 10; 8 | 9 | using namespace std; 10 | 11 | int main() 12 | { 13 | double fuck[k]; 14 | int n = Fill_array(fuck, k); 15 | Show_array(fuck, n); 16 | Reverse_array(fuck, n); 17 | 18 | for (int i = 0; i < n; i++) 19 | { 20 | cout << fuck[i] << " "; 21 | } 22 | 23 | cout << endl; 24 | double temp; 25 | temp = fuck[0]; 26 | fuck[0] = fuck[n - 1]; 27 | fuck[n - 1] = temp; 28 | 29 | for (int i = 0; i < n; i++) 30 | { 31 | cout << fuck[i] << " "; 32 | } 33 | cout << endl; 34 | 35 | cout << "Done."; 36 | cout << endl; 37 | 38 | system("pause"); 39 | return 0; 40 | } 41 | 42 | 43 | int Fill_array(double ar[], int limit) 44 | { 45 | double temp; 46 | int i; 47 | for (i = 0; i < limit; i++) 48 | { 49 | cout << "Enter the numbers: " << endl; 50 | cin >> temp; 51 | if (!cin) 52 | { 53 | cin.clear(); 54 | while (cin.get() != '\n') 55 | continue; 56 | cout << "End.\n"; 57 | break; 58 | } 59 | else 60 | ar[i] = temp; 61 | } 62 | 63 | 64 | return i; 65 | 66 | 67 | 68 | } 69 | void Show_array(double ar[], int size) 70 | { 71 | for (int i = 0; i < size; i++) 72 | cout << ar[i] << ' '; 73 | cout << endl; 74 | } 75 | void Reverse_array(double ar[], int size) 76 | { 77 | double temp; 78 | for (int i = 0; i < size / 2; i++) { 79 | temp = ar[i]; 80 | ar[i] = ar[size - i-1]; 81 | ar[size - i-1] = temp; 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/myCode/7/7/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | const int Max = 5; 5 | 6 | int fill_array(double*pBeg, const double*pEnd) 7 | { 8 | using namespace std; 9 | double temp; 10 | int i = 0; 11 | while (pBeg < pEnd) 12 | { 13 | cout << "Enter value #" << i++ << ":"; 14 | cin >> temp; 15 | if (!cin) 16 | { 17 | cin.clear(); 18 | while (cin.get() != '\n') 19 | continue; 20 | cout << "Bad input;input process terminated.\n"; 21 | break; 22 | } 23 | else if (temp < 0) 24 | break; 25 | *pBeg = temp; 26 | ++pBeg; 27 | 28 | } 29 | return i; 30 | } 31 | 32 | void show_array(const double* pBeg, const double*pEnd) 33 | { 34 | using namespace std; 35 | for (int i = 0; pBeg < pEnd; ++pBeg) 36 | { 37 | cout << "Property #" << (i + 1) << ": $"; 38 | cout << *pBeg << endl; 39 | } 40 | } 41 | 42 | void revalue(double r, double*pBeg, const double*pEnd) 43 | { 44 | while (pBeg < pEnd) 45 | { 46 | *pBeg *= r; 47 | ++pBeg; 48 | } 49 | } 50 | 51 | int main() 52 | { 53 | using namespace std; 54 | double properties[Max]; 55 | int size = fill_array(properties, properties + Max); 56 | show_array(properties, properties + size); 57 | if (size > 0) 58 | { 59 | cout << "Enter revaluation factor: "; 60 | double factor; 61 | while (!(cin >> factor)) 62 | { 63 | cin.clear(); 64 | while (cin.get() != '\n') 65 | continue; 66 | cout << "Bad input;Please enter a number: "; 67 | } 68 | revalue(factor, properties, properties + size); 69 | show_array(properties, properties + size); 70 | } 71 | 72 | cout << "Done\n"; 73 | system("pause"); 74 | return 0; 75 | } 76 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/myCode/7/8/a/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | const int Seasons = 4; 7 | 8 | const char*fuck[] = { "Spring","Summer","Autumn","Winter" }; 9 | 10 | void fill(double shabi[]); 11 | void show(double ruozhi[]); 12 | 13 | int main() 14 | { 15 | double expense[Seasons]; 16 | fill(expense); 17 | show(expense); 18 | system("pause"); 19 | return 0; 20 | } 21 | 22 | 23 | void fill(double shabi[]) 24 | { 25 | for (int i = 0; i < Seasons; i++) 26 | { 27 | cout << "Enter" << fuck[i] << " expenses: "; 28 | cin >> shabi[i]; 29 | } 30 | } 31 | 32 | void show(double ruozhi[]) 33 | { 34 | double total = 0.0; 35 | cout << "\nEXPENSES\n"; 36 | for (int i = 0; i < Seasons; i++) 37 | { 38 | cout << fuck[i] << " : $" << ruozhi[i] << endl; 39 | total += ruozhi[i]; 40 | } 41 | cout << "Total Expenses: $" << total << endl; 42 | 43 | } 44 | 45 | 46 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/myCode/7/8/b/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | const int Seasons = 4; 7 | 8 | const char*fuck[] = { "Spring","Summer","Autumn","Winter" }; 9 | 10 | struct jiba 11 | { 12 | double arr[Seasons]; 13 | }; 14 | 15 | void fill(jiba* shabi); 16 | void show(jiba ruozhi); 17 | 18 | int main() 19 | { 20 | jiba expense; 21 | fill(&expense); 22 | show(expense); 23 | system("pause"); 24 | return 0; 25 | } 26 | 27 | 28 | void fill(jiba* shabi) 29 | { 30 | for (int i = 0; i < Seasons; i++) 31 | { 32 | cout << "Enter" << fuck[i] << " expenses: "; 33 | cin >> shabi->arr[i]; 34 | } 35 | } 36 | 37 | void show(jiba ruozhi) 38 | { 39 | double total = 0.0; 40 | cout << "\nEXPENSES\n"; 41 | for (int i = 0; i < Seasons; i++) 42 | { 43 | cout << fuck[i] << " : $" << ruozhi.arr[i] << endl; 44 | total += ruozhi.arr[i]; 45 | } 46 | cout << "Total Expenses: $" << total << endl; 47 | 48 | } 49 | 50 | 51 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/myCode/8/1/源.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | unsigned int funny = 0; 7 | 8 | 9 | void fuck(const char* sb, int x=1); 10 | 11 | void fuck(const char* sb, int x) 12 | { 13 | funny++; 14 | if (x != 0) 15 | { 16 | for (int i = 0; i < funny; i++) 17 | { 18 | cout << sb << endl; 19 | } 20 | } 21 | else 22 | cout << "None!" << endl; 23 | 24 | 25 | } 26 | 27 | int main(void) 28 | { 29 | const char* sdiao = "Hello World!"; 30 | fuck(sdiao); 31 | fuck(sdiao, 7); 32 | fuck(sdiao, -1); 33 | 34 | cout << endl; 35 | system("pause"); 36 | return 0; 37 | 38 | } -------------------------------------------------------------------------------- /cpp_primer_plus_code/myCode/8/2/源.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | struct TCandyBar 8 | { 9 | string Brand; 10 | double weight; 11 | unsigned heat; 12 | }; 13 | 14 | void fuck(TCandyBar &sb, const char* Tbrand = "Millennium Munch", const double Tweight = 2.85, const unsigned Theat = 350); 15 | void shownm(TCandyBar &sb); 16 | 17 | 18 | 19 | void fuck(TCandyBar &sb, const char* Tbrand, const double Tweight, const unsigned Theat) 20 | { 21 | sb.Brand = Tbrand; 22 | sb.weight = Tweight; 23 | sb.heat = Theat; 24 | } 25 | 26 | void shownm(TCandyBar &sb) 27 | { 28 | cout << sb.Brand << " " << sb.weight << " "<< sb.heat << endl; 29 | } 30 | 31 | int main() 32 | { 33 | 34 | TCandyBar bar; 35 | fuck(bar); 36 | shownm(bar); 37 | fuck(bar, "panpan", 3.8, 300); 38 | shownm(bar); 39 | 40 | system("pause"); 41 | return 0; 42 | 43 | } -------------------------------------------------------------------------------- /cpp_primer_plus_code/myCode/8/3/源.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | string& str_upper(string & sentence); 9 | 10 | string& str_upper(string &sentence) 11 | { 12 | for (auto&e : sentence)//auto& xxx: xxx 遍历字符串 13 | e = (char)toupper(e); 14 | return sentence; 15 | } 16 | 17 | int main() 18 | { 19 | while (true) { 20 | cout << "Enter a string(q to quit): "; 21 | string fuck; 22 | getline(cin, fuck); 23 | if (!cin || "q" == fuck || "Q" == fuck) { 24 | cout << "Bye!" << endl; 25 | break; 26 | } 27 | fuck=str_upper(fuck); 28 | cout << fuck << endl; 29 | } 30 | system("pause"); 31 | return 0; 32 | } -------------------------------------------------------------------------------- /cpp_primer_plus_code/myCode/8/5/源.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | 5 | using namespace std; 6 | 7 | template 8 | void maximal(T arr[], unsigned n,T &k); 9 | 10 | template 11 | void maximal(T arr[], unsigned n,T &k) 12 | { 13 | unsigned max = 0; 14 | for (int i = 0; i < n; i++) 15 | { 16 | if (arr[i] > arr[max]) 17 | max = i; 18 | } 19 | k = arr[max]; 20 | } 21 | 22 | int main() 23 | { 24 | int arr1[6] = { 1,2,3,4,5,6 }; 25 | double arr2[4] = { 1,2,3,4 }; 26 | int x = 0; 27 | double y = 0; 28 | maximal(arr1, 6,x); 29 | maximal(arr2, 4,y); 30 | 31 | cout << x << endl << y << endl; 32 | 33 | system( "pause" ); 34 | return 0; 35 | 36 | } -------------------------------------------------------------------------------- /cpp_primer_plus_code/myCode/8/6/源.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | 5 | using namespace std; 6 | 7 | template 8 | void maximal(T arr[], unsigned n,T &k); 9 | 10 | template 11 | void maximal(T arr[], unsigned n,T &k) 12 | { 13 | unsigned max = 0; 14 | for (int i = 0; i < n; i++) 15 | { 16 | if (arr[i] > arr[max]) 17 | max = i; 18 | } 19 | k = arr[max]; 20 | } 21 | 22 | const char* 23 | maximal(const char* arr[], unsigned n) 24 | { 25 | unsigned idxMax = 0; 26 | for (unsigned i = 0; i < n; i++) { 27 | if (strlen(arr[i]) > strlen(arr[idxMax])) { 28 | idxMax = i; 29 | } 30 | } 31 | 32 | return (arr[idxMax]); 33 | } 34 | 35 | 36 | int main() 37 | { 38 | int arr1[6] = { 1,2,3,4,5,6 }; 39 | double arr2[4] = { 1,2,3,4 }; 40 | int x = 0; 41 | double y = 0; 42 | maximal(arr1, 6,x); 43 | maximal(arr2, 4,y); 44 | 45 | cout << x << endl << y << endl; 46 | 47 | const char* strArr[] = { 48 | "hahaha", 49 | "hahahaha", 50 | "haha", 51 | "ha", 52 | "hahahahahah" 53 | }; 54 | 55 | for (auto&e : strArr) { 56 | cout << e << endl; 57 | } 58 | 59 | cout << "*****" << maximal(strArr, 5) << endl; 60 | 61 | system( "pause" ); 62 | return 0; 63 | 64 | } -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | PROJECT(main) 2 | SET(SRC_LIST main.cpp) 3 | SET(CMAKE_CXX_COMPILER "clang++") 4 | SET(CMAKE_CXX_FLAGS "-std=c++11 -Werror -Weverything -Wno-float-equal -Wno-c++98-compat -Wno-c++98-compat-pedantic -Wno-global-constructors -Wno-exit-time-destructors -Wno-missing-prototypes -Wno-padded -O3") 5 | SET(CMAKE_BUILD_TYPE Release) 6 | ADD_EXECUTABLE(main ${SRC_LIST}) 7 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 10/1/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | class TBankAccount 6 | { 7 | public: 8 | TBankAccount (string name, string acc_num, unsigned balance); 9 | 10 | void showName (void) const; 11 | void showAccNum (void) const; 12 | void showBalance (void) const; 13 | 14 | void incDeposit (unsigned amount); 15 | void decDeposit (unsigned amount); 16 | 17 | private: 18 | string m_name; 19 | string m_acc_num; 20 | unsigned m_balance; 21 | }; 22 | 23 | TBankAccount::TBankAccount (string name, string acc_num, unsigned balance) 24 | { 25 | m_name = name; 26 | m_acc_num = acc_num; 27 | m_balance = balance; 28 | } 29 | 30 | void 31 | TBankAccount::showName (void) const 32 | { 33 | cout << m_name; 34 | } 35 | 36 | void 37 | TBankAccount::showAccNum (void) const 38 | { 39 | cout << m_acc_num; 40 | } 41 | 42 | void 43 | TBankAccount::showBalance (void) const 44 | { 45 | cout << m_balance; 46 | } 47 | 48 | void 49 | TBankAccount::incDeposit (unsigned amount) 50 | { 51 | m_balance += amount; 52 | } 53 | 54 | void 55 | TBankAccount::decDeposit (unsigned amount) 56 | { 57 | if (m_balance <= amount) { 58 | m_balance = 0; 59 | } else { 60 | m_balance -= amount; 61 | } 62 | } 63 | 64 | int 65 | main (void) 66 | { 67 | TBankAccount yangyang("yangyang", "1", 1024); 68 | yangyang.showName(); 69 | cout << endl; 70 | yangyang.showAccNum(); 71 | cout << endl; 72 | yangyang.showBalance(); 73 | cout << endl; 74 | 75 | yangyang.incDeposit(128); 76 | cout << endl; 77 | yangyang.showBalance(); 78 | cout << endl; 79 | 80 | yangyang.decDeposit(2048); 81 | cout << endl; 82 | yangyang.showBalance(); 83 | cout << endl; 84 | 85 | 86 | cout << endl; 87 | return (0); 88 | } 89 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 10/2/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | class Person { 7 | private: 8 | static const unsigned LIMIT = 25; 9 | string lname; 10 | // Person’s last name 11 | char fname[LIMIT]; // Person’s first name 12 | public: 13 | Person() {lname = ""; fname[0] = '\0'; } // #1 14 | Person(const string & ln, const char * fn = "Heyyou"); 15 | // the following methods display lname and fname 16 | void Show() const; // firstname lastname format 17 | void FormalShow() const; // lastname, firstname format 18 | }; 19 | 20 | Person::Person(const string & ln, const char * fn) 21 | { 22 | lname = ln; 23 | strcpy(fname, fn); 24 | } 25 | 26 | void 27 | Person::Show() const 28 | { 29 | cout << fname << ' ' << lname; 30 | } 31 | 32 | void 33 | Person::FormalShow() const 34 | { 35 | cout << lname << ", " << fname; 36 | } 37 | 38 | int 39 | main (void) 40 | { 41 | Person one; 42 | Person two("Smythecraft"); 43 | Person three("Dimwiddy", "Sam"); 44 | three.Show(); 45 | cout << endl; 46 | three.FormalShow(); 47 | 48 | cout << endl; 49 | return (0); 50 | } 51 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 10/3/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | PROJECT(main) 2 | SET(SRC_LIST main.cpp golf.cpp) 3 | SET(CMAKE_CXX_COMPILER "clang++") 4 | SET(CMAKE_CXX_FLAGS "-std=c++11 -Werror -Weverything -Wno-c++98-compat -Wc++98-compat-pedantic -Wno-float-equal -Wno-global-constructors -Wno-exit-time-destructors -Wno-missing-prototypes -O3") 5 | SET(CMAKE_BUILD_TYPE Release) 6 | ADD_EXECUTABLE(main ${SRC_LIST}) 7 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 10/3/golf.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include "golf.h" 4 | 5 | using std::cin; 6 | using std::cout; 7 | using std::endl; 8 | using std::string; 9 | 10 | golf::golf (const char * name, int hc) 11 | { 12 | strcpy(fullname, name); 13 | handicap = hc; 14 | } 15 | 16 | int 17 | golf::setgolf (void) 18 | { 19 | cout << "输入姓名:"; 20 | string strTmp; 21 | getline(cin, strTmp); 22 | if ("" == strTmp) { 23 | return (0); 24 | } 25 | 26 | cout << "输入差点:"; 27 | int n; 28 | cin >> n; 29 | cin.get(); 30 | if (!n) { 31 | return (0); 32 | } 33 | 34 | *this = golf(strTmp.c_str(), n); 35 | 36 | return (1); 37 | } 38 | 39 | void 40 | golf::sethandicap(int hc) 41 | { 42 | handicap = hc; 43 | } 44 | 45 | void 46 | golf::showgolf(void) const 47 | { 48 | cout << fullname << '\t' << handicap; 49 | } 50 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 10/3/golf.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | class golf 4 | { 5 | public: 6 | golf (const char * name = "", int hc = 0); 7 | 8 | // interactive version: 9 | // function solicits name and handicap from user 10 | // and sets the members of g to the values entered 11 | // returns 1 if name is entered, 0 if name is empty string 12 | int setgolf(void); 13 | 14 | // function resets handicap to new value 15 | void sethandicap(int hc); 16 | 17 | // function displays contents of golf structure 18 | void showgolf(void) const; 19 | 20 | private: 21 | static const int Len = 40; 22 | char fullname[Len]; 23 | int handicap; 24 | }; 25 | 26 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 10/3/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include "golf.h" 4 | 5 | using namespace std; 6 | 7 | 8 | int 9 | main (void) 10 | { 11 | const unsigned k_size = 4; 12 | golf golfers[k_size]; 13 | unsigned numGolfers = 0; 14 | while (numGolfers < k_size && golfers[numGolfers].setgolf()) { 15 | ++numGolfers; 16 | } 17 | 18 | for (unsigned i = 0; i < numGolfers; ++i) { 19 | golfers[i].showgolf(); 20 | cout << endl; 21 | } 22 | 23 | 24 | cout << endl; 25 | return (0); 26 | } 27 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 10/4/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | PROJECT(main) 2 | SET(SRC_LIST main.cpp Sales.cpp) 3 | SET(CMAKE_CXX_COMPILER "clang++") 4 | SET(CMAKE_CXX_FLAGS "-std=c++11 -Werror -Weverything -Wno-float-equal -Wno-c++98-compat -Wno-c++98-compat-pedantic -Wno-global-constructors -Wno-exit-time-destructors -Wno-missing-prototypes -Wno-padded -O3") 5 | SET(CMAKE_BUILD_TYPE Release) 6 | ADD_EXECUTABLE(main ${SRC_LIST}) 7 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 10/4/Sales.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include "Sales.h" 4 | 5 | namespace SALES 6 | { 7 | using std::cin; 8 | using std::cout; 9 | using std::endl; 10 | using std::string; 11 | 12 | Sales::Sales (double arr[], int n) 13 | { 14 | unsigned times = n < QUARTERS ? (unsigned)n : QUARTERS; 15 | for (unsigned i = 0; i < times; ++i) { 16 | sales[i] = arr[i]; 17 | } 18 | for (unsigned i = times; i < QUARTERS; ++i) { 19 | sales[i] = 0; 20 | } 21 | 22 | size = times; 23 | average = calcAverage(); 24 | max = calcMax(); 25 | min = calcMin(); 26 | } 27 | 28 | void 29 | Sales::setSales(void) 30 | { 31 | cout << "输入" << QUARTERS << "个销售记录:"; 32 | size = QUARTERS; 33 | for (unsigned i = 0; i < QUARTERS; ++i) { 34 | cin >> sales[i]; 35 | if (!cin) { 36 | size = i; 37 | break; 38 | } 39 | } 40 | for (unsigned i = (unsigned)size; i < QUARTERS; ++i) { 41 | sales[i] = 0; 42 | } 43 | 44 | cin.clear(); 45 | cin.ignore(std::numeric_limits::max(), '\n'); 46 | 47 | average = calcAverage(); 48 | max = calcMax(); 49 | min = calcMin(); 50 | } 51 | 52 | double 53 | Sales::calcAverage (void) const 54 | { 55 | double sum = 0; 56 | for (unsigned i = 0; i < size; ++i) { 57 | sum += sales[i]; 58 | } 59 | 60 | return (sum / size); 61 | } 62 | 63 | double 64 | Sales::calcMax (void) const 65 | { 66 | unsigned idxMax = 0; 67 | for (unsigned i = 0; i < size; ++i) { 68 | if (sales[i] > sales[idxMax]) { 69 | idxMax = i; 70 | } 71 | } 72 | 73 | return (sales[idxMax]); 74 | } 75 | 76 | double 77 | Sales::calcMin (void) const 78 | { 79 | unsigned idxMin = 0; 80 | for (unsigned i = 0; i < size; ++i) { 81 | if (sales[i] < sales[idxMin]) { 82 | idxMin = i; 83 | } 84 | } 85 | 86 | return (sales[idxMin]); 87 | } 88 | 89 | void 90 | Sales::showSales (void) const 91 | { 92 | cout << "sales: "; 93 | for (const auto& e : sales) { 94 | cout << e << ' '; 95 | } 96 | cout << endl; 97 | cout << "average: " << average << endl; 98 | cout << "max: " << max << endl; 99 | cout << "min: " << min << endl; 100 | } 101 | } 102 | 103 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 10/4/Sales.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | namespace SALES 3 | { 4 | class Sales 5 | { 6 | private: 7 | static const int QUARTERS = 4; 8 | double sales[QUARTERS]; 9 | double size; 10 | double average; 11 | double max; 12 | double min; 13 | 14 | private: 15 | double calcAverage (void) const; 16 | double calcMax (void) const; 17 | double calcMin (void) const; 18 | 19 | public: 20 | Sales () {setSales();} 21 | Sales (double arr[], int n); 22 | void setSales(void); 23 | void showSales(void) const; 24 | }; 25 | } 26 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 10/4/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "Sales.h" 3 | 4 | using namespace std; 5 | 6 | int 7 | main (void) 8 | { 9 | using namespace SALES; 10 | 11 | Sales salesBook; 12 | salesBook.showSales(); 13 | 14 | Sales salesPen; 15 | salesPen.showSales(); 16 | 17 | 18 | cout << endl; 19 | return (0); 20 | } 21 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 10/6/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | class TMove 7 | { 8 | private: 9 | double m_x; 10 | double m_y; 11 | 12 | public: 13 | TMove (double a = 0, double b = 0); 14 | void showMove (void) const; 15 | TMove add (const TMove& m) const; 16 | void reset (double a = 0, double b = 0); 17 | }; 18 | 19 | TMove::TMove (double a, double b) 20 | { 21 | m_x = a; 22 | m_y = b; 23 | } 24 | 25 | void 26 | TMove::showMove (void) const 27 | { 28 | cout << '(' << m_x << ", " << m_y << ')'; 29 | } 30 | 31 | TMove 32 | TMove::add (const TMove& m) const 33 | { 34 | return (TMove(m.m_x + m_x, m.m_y + m_y)); 35 | } 36 | 37 | void 38 | TMove::reset (double a, double b) 39 | { 40 | m_x = a; 41 | m_y = b; 42 | } 43 | 44 | int 45 | main (void) 46 | { 47 | TMove one(12, 4); 48 | one.showMove(); 49 | cout << endl; 50 | TMove two(1, 1); 51 | one.add(two).showMove(); 52 | cout << endl; 53 | one.reset(); 54 | one.showMove(); 55 | 56 | 57 | cout << endl; 58 | return (0); 59 | } 60 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 10/7/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | class TPlorg 7 | { 8 | private: 9 | static const unsigned mk_size = 20; 10 | 11 | private: 12 | char m_name[mk_size]; 13 | unsigned m_contentment_idx; 14 | 15 | public: 16 | TPlorg (const char* name = "Plorg"); 17 | void setContentmentIdx (unsigned contentment_idx); 18 | void showPlorg (void) const; 19 | }; 20 | 21 | TPlorg::TPlorg (const char* name) 22 | { 23 | m_contentment_idx = 50; 24 | strncpy(m_name, name, mk_size-1); 25 | m_name[mk_size-1] = '\0'; 26 | } 27 | 28 | void 29 | TPlorg::setContentmentIdx (unsigned contentment_idx) 30 | { 31 | m_contentment_idx = contentment_idx; 32 | } 33 | 34 | void 35 | TPlorg::showPlorg (void) const 36 | { 37 | cout << m_name << ' ' << m_contentment_idx; 38 | } 39 | 40 | int 41 | main (void) 42 | { 43 | TPlorg plorg(); 44 | plorg.showPlorg(); 45 | cout << endl; 46 | plorg.setContentmentIdx(12); 47 | plorg.showPlorg(); 48 | 49 | 50 | cout << endl; 51 | return (0); 52 | } 53 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 10/8/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | class TList 7 | { 8 | public: 9 | typedef int Item; 10 | 11 | public: 12 | TList (const Item arr[] = NULL, unsigned n = 0); 13 | bool isFull (void) const; 14 | bool isEmpty (void) const; 15 | bool append (const Item& item); 16 | void visit (void (*pf) (Item& item)); 17 | 18 | private: 19 | static const unsigned mk_capacity = 4; 20 | 21 | private: 22 | Item m_content[mk_capacity]; 23 | unsigned m_size; 24 | 25 | }; 26 | 27 | TList::TList (const Item arr[], unsigned n) { 28 | if (NULL == arr) { 29 | m_size = 0; 30 | return; 31 | } 32 | 33 | m_size = mk_capacity < n ? mk_capacity : n; 34 | for (unsigned i = 0; i < m_size; ++i) { 35 | m_content[i] = arr[i]; 36 | } 37 | } 38 | 39 | bool 40 | TList::isFull (void) const 41 | { 42 | return (mk_capacity == m_size); 43 | } 44 | 45 | bool 46 | TList::isEmpty (void) const 47 | { 48 | return (0 == m_size); 49 | } 50 | 51 | bool 52 | TList::append (const Item& item) 53 | { 54 | if (isFull()) { 55 | return (false); 56 | } 57 | 58 | m_content[m_size++] = item; 59 | return (true); 60 | } 61 | 62 | void 63 | TList::visit (void (*pf) (Item& item)) 64 | { 65 | for (unsigned i = 0; i < m_size; ++i) { 66 | pf(m_content[i]); 67 | } 68 | } 69 | 70 | static void 71 | show (TList::Item& item) 72 | { 73 | cout << item << ' '; 74 | } 75 | 76 | int 77 | main (void) 78 | { 79 | TList one; 80 | one.visit(show); 81 | cout << endl; 82 | cout << "是否空:" << boolalpha << one.isEmpty(); 83 | cout << endl << "=========" << endl; 84 | 85 | TList::Item arr[] = {1, 2, 3}; 86 | TList two(arr, sizeof(arr)/sizeof(arr[0])); 87 | two.visit(show); 88 | cout << endl; 89 | cout << "是否满:" << two.isFull(); 90 | cout << endl; 91 | cout << "是否空:" << two.isEmpty(); 92 | cout << endl; 93 | cout << "追加一项:" << two.append(16); 94 | cout << endl; 95 | two.visit(show); 96 | cout << endl; 97 | 98 | 99 | cout << endl; 100 | return (0); 101 | } 102 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 11/1/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | PROJECT(main) 2 | SET(SRC_LIST main.cpp TVector.cpp) 3 | SET(CMAKE_CXX_COMPILER "clang++") 4 | SET(CMAKE_CXX_FLAGS "-std=c++11 -Werror -Weverything -Wno-float-equal -Wno-c++98-compat -Wno-c++98-compat-pedantic -Wno-global-constructors -Wno-exit-time-destructors -Wno-missing-prototypes -Wno-padded -O3") 5 | SET(CMAKE_BUILD_TYPE Release) 6 | ADD_EXECUTABLE(main ${SRC_LIST}) 7 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 11/1/TVector.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | 5 | namespace n_vector 6 | { 7 | using std::ostream; 8 | 9 | class TVector 10 | { 11 | public: 12 | enum Mode {RECT, POL}; // 坐标类型,依次为直角坐标、极坐标 13 | 14 | public: 15 | explicit TVector (double a = 0, double b = 0, Mode mode = RECT); // (x, y) OR (length, angle) 16 | 17 | void reset (double a = 0, double b = 0, Mode mode = RECT); 18 | 19 | void setMode (Mode mode); 20 | Mode getMode (void) const; 21 | 22 | double getX (void) const; 23 | double getY (void) const; 24 | double getLength (void) const; 25 | double getAngle (void) const; 26 | 27 | TVector operator+ (const TVector& rvalue) const; 28 | TVector& operator+= (const TVector& rvalue); 29 | TVector operator- (void) const; 30 | 31 | // ====================================== 32 | 33 | private: 34 | void m_setPolar (void); 35 | void m_setRect (void); 36 | 37 | private: 38 | double m_x; // 直角坐标的X坐标 39 | double m_y; // 直角坐标的Y坐标 40 | double m_length; // 极坐标的长度 41 | double m_angle; // 极坐标的角度 42 | Mode m_mode; 43 | }; 44 | 45 | ostream& operator<< (ostream& os, const TVector& vec); 46 | } 47 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 11/1/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include "TVector.h" 5 | 6 | using namespace std; 7 | using namespace n_vector; 8 | 9 | 10 | int 11 | main (void) 12 | { 13 | ofstream of; 14 | of.open("output.txt"); 15 | 16 | while (true) { 17 | double setp; 18 | double distance; 19 | unsigned cnt_steps = 0; 20 | 21 | cout << "输入步长:"; 22 | cin >> setp; 23 | if (!cin || setp <= 0) { 24 | break; 25 | } 26 | cin.clear(); // 清空输入缓冲区错误标志位 27 | cin.ignore(std::numeric_limits::max(), '\n'); // 清空输入缓冲区内容 28 | 29 | cout << "输入距离:"; 30 | cin >> distance; 31 | if (!cin || distance <= 0) { 32 | break; 33 | } 34 | cin.clear(); // 清空输入缓冲区错误标志位 35 | cin.ignore(std::numeric_limits::max(), '\n'); // 清空输入缓冲区内容 36 | 37 | of << "开始>>>>>>>>>>" << endl; 38 | TVector vec(0, 0, TVector::POL); 39 | srand((unsigned)time(nullptr)); 40 | while (vec.getLength() < distance) { 41 | vec += TVector(setp, rand()%361, TVector::POL); 42 | of << cnt_steps++ << ":" << vec << endl; 43 | } 44 | of << "结束<<<<<<<<<<" << endl; 45 | of << "距离" << distance << ",步长" << setp << ",历经" << cnt_steps << "步走完,终点坐标" << vec << endl; 46 | of << "==========\n" << endl; 47 | } 48 | 49 | of.close(); 50 | 51 | 52 | cout << endl; 53 | return (0); 54 | } 55 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 11/2/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | PROJECT(main) 2 | SET(SRC_LIST main.cpp TVector.cpp) 3 | SET(CMAKE_CXX_COMPILER "clang++") 4 | SET(CMAKE_CXX_FLAGS "-std=c++11 -Werror -Weverything -Wno-float-equal -Wno-c++98-compat -Wno-c++98-compat-pedantic -Wno-global-constructors -Wno-exit-time-destructors -Wno-missing-prototypes -Wno-padded -O3") 5 | SET(CMAKE_BUILD_TYPE Release) 6 | ADD_EXECUTABLE(main ${SRC_LIST}) 7 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 11/2/TVector.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | 5 | namespace n_vector 6 | { 7 | using std::ostream; 8 | 9 | class TVector 10 | { 11 | public: 12 | enum Mode {RECT, POL}; // 坐标类型,依次为直角坐标、极坐标 13 | 14 | public: 15 | explicit TVector (double a = 0, double b = 0, Mode mode = RECT); // (x, y) OR (length, angle) 16 | 17 | void reset (double a = 0, double b = 0, Mode mode = RECT); 18 | 19 | void setMode (Mode mode); 20 | Mode getMode (void) const; 21 | 22 | double getX (void) const; 23 | double getY (void) const; 24 | double getLength (void) const; 25 | double getAngle (void) const; 26 | 27 | TVector operator+ (const TVector& rvalue) const; 28 | TVector& operator+= (const TVector& rvalue); 29 | TVector operator- (void) const; 30 | 31 | // ====================================== 32 | 33 | private: 34 | void m_convertPolarToRect (double length, double angle); 35 | void m_converRectToPolar (double& length, double& angle) const; 36 | 37 | private: 38 | double m_x; // 直角坐标的X坐标 39 | double m_y; // 直角坐标的Y坐标 40 | Mode m_mode; 41 | }; 42 | 43 | ostream& operator<< (ostream& os, const TVector& vec); 44 | } 45 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 11/2/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include "TVector.h" 4 | 5 | using namespace std; 6 | using namespace n_vector; 7 | 8 | 9 | int 10 | main (void) 11 | { 12 | while (true) { 13 | double setp; 14 | double distance; 15 | unsigned cnt_steps = 0; 16 | 17 | cout << "输入步长:"; 18 | cin >> setp; 19 | if (!cin || setp <= 0) { 20 | break; 21 | } 22 | cin.clear(); // 清空输入缓冲区错误标志位 23 | cin.ignore(std::numeric_limits::max(), '\n'); // 清空输入缓冲区内容 24 | 25 | cout << "输入距离:"; 26 | cin >> distance; 27 | if (!cin || distance <= 0) { 28 | break; 29 | } 30 | cin.clear(); // 清空输入缓冲区错误标志位 31 | cin.ignore(std::numeric_limits::max(), '\n'); // 清空输入缓冲区内容 32 | 33 | cout << "开始>>>>>>>>>>" << endl; 34 | TVector vec(0, 0, TVector::POL); 35 | srand((unsigned)time(nullptr)); 36 | while (vec.getLength() < distance) { 37 | vec += TVector(setp, rand()%361, TVector::POL); 38 | cout << cnt_steps++ << ":" << vec << endl; 39 | } 40 | cout << "结束<<<<<<<<<<" << endl; 41 | cout << "距离" << distance << ",步长" << setp << ",历经" << cnt_steps << "步走完,终点坐标" << vec << endl; 42 | cout << "==========\n" << endl; 43 | } 44 | 45 | 46 | cout << endl; 47 | return (0); 48 | } 49 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 11/3/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | PROJECT(main) 2 | SET(SRC_LIST main.cpp TVector.cpp) 3 | SET(CMAKE_CXX_COMPILER "clang++") 4 | SET(CMAKE_CXX_FLAGS "-std=c++11 -Werror -Weverything -Wno-float-equal -Wno-c++98-compat -Wno-c++98-compat-pedantic -Wno-global-constructors -Wno-exit-time-destructors -Wno-missing-prototypes -Wno-padded -O3") 5 | SET(CMAKE_BUILD_TYPE Release) 6 | ADD_EXECUTABLE(main ${SRC_LIST}) 7 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 11/3/TVector.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | 5 | namespace n_vector 6 | { 7 | using std::ostream; 8 | 9 | class TVector 10 | { 11 | public: 12 | enum Mode {RECT, POL}; // 坐标类型,依次为直角坐标、极坐标 13 | 14 | public: 15 | explicit TVector (double a = 0, double b = 0, Mode mode = RECT); // (x, y) OR (length, angle) 16 | 17 | void reset (double a = 0, double b = 0, Mode mode = RECT); 18 | 19 | void setMode (Mode mode); 20 | Mode getMode (void) const; 21 | 22 | double getX (void) const; 23 | double getY (void) const; 24 | double getLength (void) const; 25 | double getAngle (void) const; 26 | 27 | TVector operator+ (const TVector& rvalue) const; 28 | TVector& operator+= (const TVector& rvalue); 29 | TVector operator- (void) const; 30 | 31 | // ====================================== 32 | 33 | private: 34 | void m_setPolar (void); 35 | void m_setRect (void); 36 | 37 | private: 38 | double m_x; // 直角坐标的X坐标 39 | double m_y; // 直角坐标的Y坐标 40 | double m_length; // 极坐标的长度 41 | double m_angle; // 极坐标的角度 42 | Mode m_mode; 43 | }; 44 | 45 | ostream& operator<< (ostream& os, const TVector& vec); 46 | } 47 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 11/3/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include "TVector.h" 4 | 5 | using namespace std; 6 | using namespace n_vector; 7 | 8 | 9 | int 10 | main (void) 11 | { 12 | srand((unsigned)time(nullptr)); 13 | while (true) { 14 | double setp; 15 | double distance; 16 | unsigned times; 17 | unsigned max_setps = 0, min_setps = numeric_limits::max(), sum_setps = 0; 18 | 19 | cout << "输入步长:"; 20 | cin >> setp; 21 | if (!cin || setp <= 0) { 22 | break; 23 | } 24 | cin.clear(); // 清空输入缓冲区错误标志位 25 | cin.ignore(std::numeric_limits::max(), '\n'); // 清空输入缓冲区内容 26 | 27 | cout << "输入距离:"; 28 | cin >> distance; 29 | if (!cin || distance <= 0) { 30 | break; 31 | } 32 | cin.clear(); // 清空输入缓冲区错误标志位 33 | cin.ignore(std::numeric_limits::max(), '\n'); // 清空输入缓冲区内容 34 | 35 | cout << "输入测试次数:"; 36 | cin >> times; 37 | if (!cin) { 38 | break; 39 | } 40 | cin.clear(); // 清空输入缓冲区错误标志位 41 | cin.ignore(std::numeric_limits::max(), '\n'); // 清空输入缓冲区内容 42 | 43 | for (unsigned i = 0; i < times; ++i) { 44 | unsigned cnt_steps = 0; 45 | TVector vec(0, 0, TVector::POL); 46 | 47 | cout << i << ":"; 48 | while (vec.getLength() < distance) { 49 | vec += TVector(setp, rand()%360, TVector::POL); 50 | ++cnt_steps; 51 | } 52 | cout << cnt_steps << "步走到" << vec << endl; 53 | 54 | if (cnt_steps > max_setps) { 55 | max_setps = cnt_steps; 56 | } 57 | if (cnt_steps < min_setps) { 58 | min_setps = cnt_steps; 59 | } 60 | sum_setps += cnt_steps; 61 | } 62 | cout << "距离" << distance << ",步长" << setp << ",测试" << times << "次,最多走" 63 | << max_setps << "步,最少走" << min_setps << "步,平均走" << sum_setps / times << "步" << endl; 64 | cout << "==========" << endl; 65 | } 66 | 67 | 68 | cout << endl; 69 | return (0); 70 | } 71 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 11/4/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | PROJECT(main) 2 | SET(SRC_LIST main.cpp TTime.cpp) 3 | SET(CMAKE_CXX_COMPILER "clang++") 4 | SET(CMAKE_CXX_FLAGS "-std=c++11 -Werror -Weverything -Wno-float-equal -Wno-c++98-compat -Wno-c++98-compat-pedantic -Wno-global-constructors -Wno-exit-time-destructors -Wno-missing-prototypes -Wno-padded -O3") 5 | SET(CMAKE_BUILD_TYPE Release) 6 | ADD_EXECUTABLE(main ${SRC_LIST}) 7 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 11/4/TTime.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | 5 | namespace n_time 6 | { 7 | class TTime 8 | { 9 | public: 10 | explicit TTime (unsigned hour = 0, unsigned minute = 0, unsigned second = 0); 11 | 12 | public: 13 | void add (unsigned hour = 0, unsigned minute = 0, unsigned second = 0); 14 | void reset (unsigned hour = 0, unsigned minute = 0, unsigned second = 0); 15 | unsigned getSecond (void) const; 16 | unsigned getMinute (void) const; 17 | unsigned getHour (void) const; 18 | 19 | friend TTime operator+ (const TTime& lvalue, const TTime& rvalue); 20 | friend TTime operator- (const TTime& lvalue, const TTime& rvalue); 21 | friend TTime operator* (const TTime& lvalue, double n); 22 | friend TTime operator* (double n, const TTime& rvalue); 23 | friend std::ostream& operator<< (std::ostream& os, const TTime& time); 24 | 25 | private: 26 | unsigned m_second; 27 | unsigned m_minute; 28 | unsigned m_hour; 29 | }; 30 | } 31 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 11/4/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "TTime.h" 3 | 4 | using namespace std; 5 | using namespace n_time; 6 | 7 | 8 | int 9 | main (void) 10 | { 11 | TTime time1(1, 65, 60); 12 | cout << time1 << endl; 13 | TTime time2(8, 25); 14 | cout << time2 << endl; 15 | cout << time1 + time2 << endl; 16 | cout << time1 - time2 << endl; 17 | 18 | cout << "=========" << endl; 19 | time1.add(1, 55, 30); 20 | cout << time1 << endl; 21 | 22 | cout << "=========" << endl; 23 | time1.reset(32, 64, 128); 24 | cout << time1 << endl; 25 | 26 | cout << "=========" << endl; 27 | cout << time1 * 1.5 << endl; 28 | cout << 1.5 * time1 << endl; 29 | 30 | 31 | cout << endl; 32 | return (0); 33 | } 34 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 11/7/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | PROJECT(main) 2 | SET(SRC_LIST main.cpp TComplex.cpp) 3 | SET(CMAKE_CXX_COMPILER "clang++") 4 | SET(CMAKE_CXX_FLAGS "-std=c++11 -Werror -Weverything -Wno-float-equal -Wno-c++98-compat -Wno-c++98-compat-pedantic -Wno-global-constructors -Wno-exit-time-destructors -Wno-missing-prototypes -Wno-padded -O3") 5 | SET(CMAKE_BUILD_TYPE Release) 6 | ADD_EXECUTABLE(main ${SRC_LIST}) 7 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 11/7/TComplex.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include "TComplex.h" 4 | 5 | 6 | namespace n_complex 7 | { 8 | using std::cout; 9 | using std::ostream; 10 | using std::numeric_limits; 11 | using std::streamsize; 12 | 13 | // ==================================== 14 | // 辅助函数 15 | // ==================================== 16 | 17 | // ==================================== 18 | // 成员函数 19 | // ==================================== 20 | 21 | TComplex::TComplex (double real, double imaginary) 22 | { 23 | m_real = real; 24 | m_imaginary = imaginary; 25 | } 26 | 27 | // ==================================== 28 | // 重载运算符 29 | // ==================================== 30 | 31 | ostream& 32 | operator<< (ostream& os, const TComplex& coplx) 33 | { 34 | os << '(' << coplx.m_real << ", " << coplx.m_imaginary << "i)"; 35 | return (os); 36 | } 37 | 38 | istream& 39 | operator>> (istream& is, TComplex& coplx) 40 | { 41 | cout << "real: "; 42 | is >> coplx.m_real; 43 | if (!is) { 44 | is.ignore(numeric_limits::max(), '\n'); // 清空输入缓冲区内容 45 | return (is); 46 | } 47 | 48 | cout << "imaginary: "; 49 | is >> coplx.m_imaginary; 50 | is.ignore(numeric_limits::max(), '\n'); // 清空输入缓冲区内容 51 | return (is); 52 | } 53 | 54 | TComplex 55 | operator~ (const TComplex& coplx) 56 | { 57 | return (TComplex(coplx.m_real, -coplx.m_imaginary)); 58 | } 59 | 60 | TComplex 61 | operator+ (const TComplex& lvalue, const TComplex& rvalue) 62 | { 63 | return (TComplex(lvalue.m_real + rvalue.m_real, lvalue.m_imaginary + rvalue.m_imaginary)); 64 | } 65 | 66 | TComplex 67 | operator- (const TComplex& lvalue, const TComplex& rvalue) 68 | { 69 | return (TComplex(lvalue.m_real - rvalue.m_real, lvalue.m_imaginary - rvalue.m_imaginary)); 70 | } 71 | 72 | TComplex 73 | operator* (const TComplex& lvalue, const TComplex& rvalue) 74 | { 75 | return (TComplex( lvalue.m_real * rvalue.m_real - lvalue.m_imaginary * rvalue.m_imaginary, 76 | lvalue.m_real * rvalue.m_imaginary + lvalue.m_imaginary * rvalue.m_real )); 77 | } 78 | 79 | TComplex 80 | operator* (double n, const TComplex& coplx) 81 | { 82 | return (TComplex(n*coplx.m_real, n*coplx.m_imaginary)); 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 11/7/TComplex.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | 5 | namespace n_complex 6 | { 7 | using std::ostream; 8 | using std::istream; 9 | 10 | class TComplex 11 | { 12 | public: 13 | explicit TComplex (double real = 0, double imaginary = 0); 14 | 15 | friend ostream& operator<< (ostream& os, const TComplex& coplx); 16 | friend istream& operator>> (istream& is, TComplex& coplx); 17 | friend TComplex operator~ (const TComplex& coplx); 18 | friend TComplex operator+ (const TComplex& lvalue, const TComplex& rvalue); 19 | friend TComplex operator- (const TComplex& lvalue, const TComplex& rvalue); 20 | friend TComplex operator* (const TComplex& lvalue, const TComplex& rvalue); 21 | friend TComplex operator* (double n, const TComplex& coplx); 22 | 23 | private: 24 | double m_real; 25 | double m_imaginary; 26 | }; 27 | } 28 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 11/7/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "TComplex.h" 3 | 4 | using namespace std; 5 | using namespace n_complex; 6 | 7 | int main() 8 | { 9 | TComplex a(3.0, 4.0); // initialize to (3,4i) Programming Exercises 10 | TComplex c; 11 | cout << "Enter a complex number (q to quit):\n"; 12 | while (cin >> c) 13 | { 14 | cout << "c is " << c << '\n'; 15 | cout << "complex conjugate is " << ~c << '\n'; 16 | cout << "a is " << a << "\n"; 17 | cout << "a + c is " << a + c << '\n'; 18 | cout << "a - c is " << a - c << '\n'; 19 | cout << "a * c is " << a * c << '\n'; 20 | cout << "2 * c is " << 2 * c << '\n'; 21 | cout << "Enter a complex number (q to quit):\n"; 22 | } 23 | cout << "Done!\n"; 24 | 25 | return 0; 26 | } 27 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 12/1/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | class Cow 7 | { 8 | public: 9 | //Cow(); 10 | explicit Cow(const char * nm = "", const char * ho = "", double wt = 0); 11 | Cow(const Cow & c); 12 | ~Cow(); 13 | Cow & operator=(const Cow & c); 14 | void ShowCow() const; // display all cow data 15 | 16 | private: 17 | char name[20]; 18 | char* hobby; 19 | double weight; 20 | }; 21 | 22 | Cow::Cow (const char * nm, const char * ho, double wt) 23 | : weight(wt) 24 | { 25 | unsigned str_len = strlen(nm) < 20-1 ? strlen(nm) : 20-1; 26 | strncpy(name, nm, str_len); 27 | name[str_len] = '\0'; 28 | 29 | hobby = new char [strlen(ho)+1]; 30 | strcpy(hobby, ho); 31 | } 32 | 33 | Cow::Cow (const Cow& c) 34 | : weight(c.weight) 35 | { 36 | strcpy(name, c.name); 37 | 38 | hobby = new char [strlen(c.hobby)+1]; 39 | strcpy(hobby, c.hobby); 40 | } 41 | 42 | Cow::~Cow () 43 | { 44 | delete [] hobby; 45 | } 46 | 47 | void 48 | Cow::ShowCow () const 49 | { 50 | cout << name << '\t' << hobby << '\t' << weight; 51 | } 52 | 53 | Cow& 54 | Cow::operator= (const Cow & c) 55 | { 56 | if (&c == this) { 57 | return (*this); 58 | } 59 | 60 | strcpy(name, c.name); 61 | 62 | delete [] hobby; 63 | hobby = new char [strlen(c.hobby)+1]; 64 | strcpy(hobby, c.hobby); 65 | 66 | weight = c.weight; 67 | 68 | return (*this); 69 | } 70 | 71 | int 72 | main (void) 73 | { 74 | Cow cow1("cow1", "eat", 405.5); 75 | cout << "cow1: "; 76 | cow1.ShowCow(); 77 | cout << endl; 78 | 79 | Cow cow2; 80 | cout << "cow2: "; 81 | cow2.ShowCow(); 82 | cout << endl; 83 | 84 | Cow cow3(cow1); 85 | cout << "cow3: "; 86 | cow3.ShowCow(); 87 | cout << endl; 88 | 89 | Cow cow4; 90 | cow4 = cow1; 91 | cout << "cow4: "; 92 | cow4.ShowCow(); 93 | cout << endl; 94 | 95 | 96 | cout << endl; 97 | return (0); 98 | } 99 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 12/2/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | PROJECT(main) 2 | SET(SRC_LIST main.cpp TString.cpp) 3 | SET(CMAKE_CXX_COMPILER "clang++") 4 | SET(CMAKE_CXX_FLAGS "-std=c++11 -Werror -Weverything -Wno-float-equal -Wno-c++98-compat -Wno-c++98-compat-pedantic -Wno-global-constructors -Wno-exit-time-destructors -Wno-missing-prototypes -Wno-padded -O3") 5 | SET(CMAKE_BUILD_TYPE Release) 6 | ADD_EXECUTABLE(main ${SRC_LIST}) 7 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 12/2/TString.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | 5 | namespace n_string 6 | { 7 | class TString 8 | { 9 | public: 10 | static const unsigned k_buffer_max_size = 256; 11 | 12 | public: 13 | TString (const char* text = ""); // !非explicit 14 | TString (const TString& str); 15 | ~TString (); 16 | 17 | unsigned getLength (void) const; 18 | 19 | const char* toCstr (void) const; 20 | 21 | void stringup (void); 22 | void stringlow (void); 23 | 24 | unsigned has (char ch) const; 25 | 26 | TString& operator= (const TString& str); 27 | TString& operator+= (const TString& str); 28 | 29 | char& operator[] (unsigned idx); 30 | const char& operator[] (unsigned idx) const; 31 | 32 | friend std::istream& operator>> (std::istream& is, TString& str); 33 | 34 | 35 | private: 36 | void m_assignMember (const char* text); 37 | 38 | private: 39 | char* mp_text; 40 | unsigned m_text_length; 41 | }; 42 | 43 | std::ostream& operator<< (std::ostream& os, const TString& str); 44 | 45 | bool operator< (const TString& lvalue, const TString& rvalue); 46 | bool operator> (const TString& lvalue, const TString& rvalue); 47 | bool operator== (const TString& lvalue, const TString& rvalue); 48 | bool operator<= (const TString& lvalue, const TString& rvalue); 49 | bool operator>= (const TString& lvalue, const TString& rvalue); 50 | 51 | TString operator+ (const TString& lvalue, const TString& rvalue); 52 | } 53 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 12/2/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "TString.h" 3 | 4 | using namespace std; 5 | using namespace n_string; 6 | 7 | int main() 8 | { 9 | TString s1(" and I am a C++ student."); 10 | TString s2 = "Please enter your name: "; 11 | TString s3; 12 | cout << s2; 13 | // overloaded << operator 14 | cin >> s3; 15 | // overloaded >> operator 16 | s2 = "My name is " + s3; 17 | // overloaded =, + operators 18 | cout << s2 << ".\n"; 19 | s2 = s2 + s1; 20 | s2.stringup(); 21 | // converts string to uppercase 22 | cout << "The string\n" << s2 << "\ncontains " << s2.has('A') 23 | << " 'A' characters in it.\n"; 24 | s1 = "red"; 25 | // tstring(const char *), 26 | // then tstring & operator=(const string&) 27 | TString rgb[3] = { TString(s1), TString("green"), TString("blue")}; 28 | cout << "enter the name of a primary color for mixing light: "; 29 | TString ans; 30 | bool success = false; 31 | while (cin >> ans) 32 | { 33 | ans.stringlow(); 34 | // converts string to lowercase 35 | for (int i = 0; i < 3; i++) 36 | { 37 | if (ans == rgb[i]) // overloaded == operator 38 | { 39 | cout << "That's right!\n"; 40 | success = true; 41 | break; 42 | } 43 | } 44 | if (success) 45 | break; 46 | else 47 | cout << "Try again!\n"; 48 | } 49 | cout << "Bye\n"; 50 | return 0; 51 | } 52 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 13/4/answer: -------------------------------------------------------------------------------- 1 | b)由于 Port 存在深拷贝的需要,拷贝构造函数 Port(const Port & p)、析构函数 ~Port()、赋值运算符重载 Port & operator=(const Port & p) 等三个成员函数不能使用编译器自动生成的潜拷贝版本,所以必须重写定义;其他成员函数编译器不会自动生成,按功能需要,必须得自行定义; 2 | 3 | c)语法上,operator=()可声明为虚函数,语义上,operator=()声明为虚函数是无意义的且易导致误解。派生类虚函数必须与基类虚函数的函数签名必须一致才能产生多态特性,而声明operator=()时,基类为operator=(const Port& port)、派生类为operator=(const VintagePort& vintage),两者函数签名不一致,即便声明为virtual,也无法体现出多态特性,故,通常不将operator=()定为虚函数,声明虚函数反而容易引起误解; 4 | operator<<() 为友元而非成员函数,不满足“只有成员函数才能成为虚函数”的语法要求; 5 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 14/1/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | PROJECT(main) 2 | SET(SRC_LIST main.cpp Wine.cpp) 3 | SET(CMAKE_CXX_COMPILER "clang++") 4 | SET(CMAKE_CXX_FLAGS "-std=c++11 -Werror -Weverything -Wno-float-equal -Wno-c++98-compat -Wno-c++98-compat-pedantic -Wno-global-constructors -Wno-exit-time-destructors -Wno-missing-prototypes -Wno-padded -O3") 5 | SET(CMAKE_BUILD_TYPE Release) 6 | ADD_EXECUTABLE(main ${SRC_LIST}) 7 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 14/1/Wine.cpp: -------------------------------------------------------------------------------- 1 | #include "Wine.h" 2 | 3 | 4 | namespace n_wine 5 | { 6 | using std::cin; 7 | using std::cout; 8 | using std::endl; 9 | using std::cerr; 10 | 11 | // ==================================== 12 | // 公有成员函数 13 | // ==================================== 14 | 15 | Wine::Wine (const string& name, unsigned years_total, unsigned vintage_years[], unsigned bottles_total[]) 16 | : name_(name), 17 | years_total_(years_total), 18 | vintage_year_and_bottles_total_(UnsignedArray(vintage_years, years_total), UnsignedArray(bottles_total, years_total)) 19 | { 20 | ; 21 | } 22 | 23 | Wine::Wine (const string& name, unsigned years_total) 24 | : name_(name), 25 | years_total_(years_total), 26 | vintage_year_and_bottles_total_(UnsignedArray(years_total), UnsignedArray(years_total)) 27 | { 28 | ; 29 | } 30 | 31 | const string& 32 | Wine::getLabel (void) const 33 | { 34 | return (name_); 35 | } 36 | 37 | void 38 | Wine::getBottles (void) 39 | { 40 | cout << "Enter "<< name_ << " data for " << years_total_ << " year(s) ---- \n"; 41 | 42 | for (unsigned i = 0; i < years_total_; ++i) { 43 | unsigned vintage_year; 44 | cout << "Enter year: "; 45 | cin >> vintage_year; 46 | if (!cin) { 47 | cerr << "ERREOR! " << __FILE__ << ", " << __LINE__ << endl; 48 | exit(EXIT_FAILURE); 49 | } 50 | vintage_year_and_bottles_total_.first[i] = vintage_year; 51 | 52 | unsigned bottles_total; 53 | cout << "Enter bottles for that year: "; 54 | cin >> bottles_total; 55 | if (!cin) { 56 | cerr << "ERREOR! " << __FILE__ << ", " << __LINE__ << endl; 57 | exit(EXIT_FAILURE); 58 | } 59 | vintage_year_and_bottles_total_.second[i] = bottles_total; 60 | } 61 | } 62 | 63 | void 64 | Wine::show (void) const 65 | { 66 | cout << "Wine: " << name_ << '\n'; 67 | 68 | cout << '\t' << "Year" << '\t' << "Bottles" << '\n'; 69 | for (unsigned i = 0; i < years_total_; ++i) { 70 | cout << '\t' << vintage_year_and_bottles_total_.first[i] << '\t' << vintage_year_and_bottles_total_.second[i] << endl; 71 | } 72 | } 73 | 74 | unsigned 75 | Wine::sum (void) const 76 | { 77 | return (vintage_year_and_bottles_total_.second.sum()); 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 14/1/Wine.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | #include 5 | 6 | namespace n_wine 7 | { 8 | using std::string; 9 | using std::pair; 10 | using std::valarray; 11 | 12 | class Wine 13 | { 14 | private: 15 | typedef valarray UnsignedArray; 16 | 17 | public: 18 | Wine (const string& name, unsigned years_total, unsigned vintage_years[], unsigned bottles_total[]); 19 | Wine (const string& name, unsigned years_total); 20 | const string& getLabel (void) const; 21 | void getBottles (void); 22 | void show (void) const; 23 | unsigned sum (void) const; 24 | 25 | private: 26 | const string name_; 27 | const unsigned years_total_; // 年份数量 28 | pair vintage_year_and_bottles_total_; // 酿造年份与对应瓶数 29 | }; 30 | } 31 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 14/1/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "Wine.h" 3 | 4 | int main ( void ) 5 | { 6 | using std::cin; 7 | using std::cout; 8 | using std::endl; 9 | using namespace n_wine; 10 | 11 | 12 | cout << "Enter name of wine: "; 13 | char lab[50]; 14 | cin.getline(lab, 50); 15 | cout << "Enter number of years: "; 16 | unsigned yrs; 17 | cin >> yrs; 18 | Wine holding(lab, yrs); // store label, years, give arrays yrs elements 19 | holding.getBottles(); // solicit input for year, bottle count 20 | holding.show(); // display object contents 21 | 22 | const unsigned YRS = 3; 23 | unsigned y[YRS] = {1993, 1995, 1998}; 24 | unsigned b[YRS] = { 48, 60, 72}; 25 | // create new object, initialize using data in arrays y and b 26 | Wine more("Gushing Grape Red",YRS, y, b); 27 | more.show(); 28 | cout << "Total bottles for " << more.getLabel() // use Label() method 29 | << ": " << more.sum() << endl; // use sum() method 30 | cout << "Bye\n"; 31 | 32 | return 0; 33 | } 34 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 14/2/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | PROJECT(main) 2 | SET(SRC_LIST main.cpp Wine.cpp) 3 | SET(CMAKE_CXX_COMPILER "clang++") 4 | SET(CMAKE_CXX_FLAGS "-std=c++11 -Werror -Weverything -Wno-float-equal -Wno-c++98-compat -Wno-c++98-compat-pedantic -Wno-global-constructors -Wno-exit-time-destructors -Wno-missing-prototypes -Wno-padded -O3") 5 | SET(CMAKE_BUILD_TYPE Release) 6 | ADD_EXECUTABLE(main ${SRC_LIST}) 7 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 14/2/Wine.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | #include 5 | 6 | namespace n_wine 7 | { 8 | using std::string; 9 | using std::pair; 10 | using std::valarray; 11 | 12 | typedef valarray UnsignedArray; 13 | 14 | class Wine : private string, private pair 15 | { 16 | public: 17 | Wine (const string& name, unsigned years_total, unsigned vintage_years[], unsigned bottles_total[]); 18 | Wine (const string& name, unsigned years_total); 19 | const string& getLabel (void) const; 20 | void getBottles (void); 21 | void show (void) const; 22 | unsigned sum (void) const; 23 | 24 | private: 25 | //const string name_; 26 | const unsigned years_total_; // 年份数量 27 | // vintage_year_and_bottles_total_; // 酿造年份与对应瓶数 28 | }; 29 | } 30 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 14/2/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "Wine.h" 3 | 4 | int main ( void ) 5 | { 6 | using std::cin; 7 | using std::cout; 8 | using std::endl; 9 | using namespace n_wine; 10 | 11 | 12 | cout << "Enter name of wine: "; 13 | char lab[50]; 14 | cin.getline(lab, 50); 15 | cout << "Enter number of years: "; 16 | unsigned yrs; 17 | cin >> yrs; 18 | Wine holding(lab, yrs); // store label, years, give arrays yrs elements 19 | holding.getBottles(); // solicit input for year, bottle count 20 | holding.show(); // display object contents 21 | 22 | const unsigned YRS = 3; 23 | unsigned y[YRS] = {1993, 1995, 1998}; 24 | unsigned b[YRS] = { 48, 60, 72}; 25 | // create new object, initialize using data in arrays y and b 26 | Wine more("Gushing Grape Red",YRS, y, b); 27 | more.show(); 28 | cout << "Total bottles for " << more.getLabel() // use Label() method 29 | << ": " << more.sum() << endl; // use sum() method 30 | cout << "Bye\n"; 31 | 32 | return 0; 33 | } 34 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 14/5/answer: -------------------------------------------------------------------------------- 1 | Why is no assignment operator defined? 2 | ——abstr_emp、employee、manager、fink、highfink 等五个类内部并未涉及动态内存分配,并非深拷贝,因此,无须定义赋值运算符、拷贝构造函数、析构函数。 3 | 4 | Why are ShowAll() and SetAll() virtual? 5 | 为什么要将 ShowAll() 和 SetAll() 定义为虚的? 6 | ——各级派生类均有各自新增的数据成员,显示、设置新增数据成员必须由派生类自行负责,无法直接复用基类的 ShowAll() 和 SetAll() 成员函数,在这两类操作上,派生类需要体现出类的多态特性。 7 | 8 | Why is abstr_emp a virtual base class? 9 | ——若 abstr_emp 按一般方式派生出 manager、fink,而 manager、fink 派生出 highfink,highfink 将包含两份 abstr_emp 的数据成员,必须将 abstr_emp 通过 virtual 方式派生出 manager、fink,才能正常地只包含一份 abstr_emp 的数据成员。 10 | 11 | Why does the highfink class have no data section? 12 | ——highfink 通过 manager、fink 多重继承而来,无须新增数据成员。 13 | 14 | Why is only one version of operator<<() needed? 15 | ——friend std::ostream & operator<<(std::ostream & os, const abstr_emp & e) 的形参是基类引用,各派生类实现了各自的 virtual ShowAll() 函数,因此,operator<<() 在内部通过多态特性调用基类和派生类各自的 ShowAll() 实现输出。但是,书上的原型声明 virtual void ShowAll() const 有误,应改为 virtual std::ostream& ShowAll(std::ostream& os) const; 16 | 17 | What would happen if the end of the program were replaced with this code? 18 | abstr_emp tri[4] = {em, fi, hf, hf2}; 19 | for (int i = 0; i < 4; i++) 20 | tri[i].ShowAll(); 21 | ——语法错误,由于 abstr_emp 中含有纯虚成员函数,所以 abstr_emp 为抽象类,抽象类无法创建对象。 22 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 16/1/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | static bool 8 | isPalindrome (const string& word) 9 | { 10 | string word_reverse(word.crbegin(), word.crend()); 11 | return (word == word_reverse); 12 | } 13 | 14 | int 15 | main (void) 16 | { 17 | cout << "输入单词:" << endl; 18 | string word; 19 | while (cin >> word) { 20 | cout << word << (isPalindrome(word) ? "是" : "不是") << "回文" << endl; 21 | } 22 | cout << endl; 23 | 24 | return (EXIT_SUCCESS); 25 | } 26 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 16/2/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | static bool 9 | isPalindrome (const string& word) 10 | { 11 | string word_pure; 12 | for (auto& e : word) { 13 | if (isalpha(e)) { 14 | word_pure.push_back(static_cast(tolower(e))); 15 | } 16 | } 17 | string word_reverse(word_pure.crbegin(), word_pure.crend()); 18 | return (word_pure == word_reverse); 19 | } 20 | 21 | int 22 | main (void) 23 | { 24 | cout << "输入单词:" << endl; 25 | string word; 26 | while (getline(cin, word)) { 27 | cout << word << (isPalindrome(word) ? "是" : "不是") << "回文" << endl; 28 | } 29 | cout << endl; 30 | 31 | return (EXIT_SUCCESS); 32 | } 33 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 16/4/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | static int 8 | reduce (long ar[], int n) 9 | { 10 | sort(ar, ar+n); 11 | const auto iter_end = unique(ar, ar+n); 12 | return (distance(ar, iter_end)); 13 | } 14 | 15 | int 16 | main (void) 17 | { 18 | long ar[] = {13, 22, 1, 43, 1, 13, 22, 13}; 19 | copy(ar, ar + sizeof(ar)/sizeof(ar[0]), ostream_iterator(cout, " ")); 20 | cout << endl << endl; 21 | 22 | int ar_size = reduce(ar, sizeof(ar)/sizeof(ar[0])); 23 | cout << "剔重后剩下" << ar_size << "个元素:"; 24 | copy(ar, ar + ar_size, ostream_iterator(cout, " ")); 25 | cout << endl; 26 | 27 | return (EXIT_SUCCESS); 28 | } 29 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 16/5/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | template 8 | int 9 | reduce (T ar[], int n) 10 | { 11 | sort(ar, ar+n); 12 | const auto iter_end = unique(ar, ar+n); 13 | return (distance(ar, iter_end)); 14 | } 15 | 16 | int 17 | main (void) 18 | { 19 | long ar[] = {13, 22, 1, 43, 1, 13, 22, 13}; 20 | copy(ar, ar + sizeof(ar)/sizeof(ar[0]), ostream_iterator(cout, " ")); 21 | cout << endl; 22 | int ar_size = reduce(ar, sizeof(ar)/sizeof(ar[0])); 23 | cout << "剔重后剩下" << ar_size << "个元素:"; 24 | copy(ar, ar + ar_size, ostream_iterator(cout, " ")); 25 | cout << endl << endl; 26 | 27 | string ar_str[] = {"hello", "the", "who", "hello", "who"}; 28 | copy(ar_str, ar_str + sizeof(ar_str)/sizeof(ar_str[0]), ostream_iterator(cout, " ")); 29 | cout << endl; 30 | int ar_str_size = reduce(ar_str, sizeof(ar_str)/sizeof(ar_str[0])); 31 | cout << "剔重后剩下" << ar_str_size << "个元素:"; 32 | copy(ar_str, ar_str + ar_str_size, ostream_iterator(cout, " ")); 33 | cout << endl; 34 | 35 | return (EXIT_SUCCESS); 36 | } 37 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 16/7/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | static unordered_set 8 | getLotto (unsigned rang, unsigned total) 9 | { 10 | unordered_set winners; 11 | 12 | if (rang < total) { 13 | return (winners); 14 | } 15 | 16 | srand((unsigned)time(nullptr)); 17 | while (winners.size() < total) { 18 | winners.insert((unsigned)rand() % rang); 19 | } 20 | 21 | return (winners); 22 | } 23 | 24 | int 25 | main (void) 26 | { 27 | unordered_set winners = getLotto(51, 6); 28 | for (const auto& e : winners) { 29 | cout << e << ' '; 30 | } 31 | cout << endl; 32 | 33 | return (EXIT_SUCCESS); 34 | } 35 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 16/8/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | 9 | int 10 | main (void) 11 | { 12 | string full_name; 13 | 14 | cout << "输入Mat的所有朋友:" << endl; 15 | unordered_set mat_friends; 16 | while (getline(cin, full_name)) { 17 | mat_friends.insert(full_name); 18 | } 19 | cin.clear(); // 清空输入缓冲区错误标志位 20 | 21 | cout << "输入Pat的所有朋友:" << endl; 22 | unordered_set pat_friends; 23 | while (getline(cin, full_name)) { 24 | pat_friends.insert(full_name); 25 | } 26 | 27 | set all_friends; 28 | insert_iterator> insert_iter(all_friends, all_friends.cbegin()); 29 | set_union(mat_friends.cbegin(), mat_friends.cend(), pat_friends.cbegin(), pat_friends.cend(), insert_iter); 30 | cout << "所有朋友如下:" << endl; 31 | copy(all_friends.cbegin(), all_friends.cend(), ostream_iterator(cout, "\n")); 32 | cout << endl; 33 | 34 | return (EXIT_SUCCESS); 35 | } 36 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 16/9/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | 8 | using namespace std; 9 | 10 | int 11 | main (void) 12 | { 13 | unsigned elem_size; 14 | cout << "输入元素数量:"; 15 | cin >> elem_size; 16 | if (!cin) { 17 | cerr << "元素数量必须为正数!" << endl; 18 | return (EXIT_FAILURE); 19 | } 20 | cout << endl; 21 | 22 | cout << "vi0 产生" << elem_size << "个随机数" << flush; 23 | vector vi0; 24 | srand((unsigned)time(nullptr)); 25 | for (unsigned i = 0; i < elem_size; ++i) { 26 | vi0.push_back(rand()); 27 | } 28 | cout << endl; 29 | 30 | cout << "vi1 使用 sort() 泛型算法排序耗时:" << flush; 31 | vector vi1(vi0); 32 | clock_t start = clock(); 33 | sort(vi1.begin(), vi1.end()); 34 | clock_t end = clock(); 35 | cout << (double)(end - start) / CLOCKS_PER_SEC << "秒" << endl; 36 | 37 | cout << "li1 使用 sort() 容器类成员函数排序耗时:" << flush; 38 | list li1(vi0.cbegin(), vi0.cend()); 39 | start = clock(); 40 | li1.sort(); 41 | end = clock(); 42 | cout << (double)(end - start) / CLOCKS_PER_SEC << "秒" << endl; 43 | 44 | cout << "li2 先将其元素拷贝至 vi2 中,vi2 再使用 sort() 泛型算法排序,最后 vi2 将其元素拷贝至 li2 中,总计耗时:" << flush; 45 | list li2(vi0.cbegin(), vi0.cend()); 46 | start = clock(); 47 | vector vi2(li2.cbegin(), li2.cend()); 48 | sort(vi2.begin(), vi2.end()); 49 | li2.assign(vi2.cbegin(), vi2.cend()); 50 | end = clock(); 51 | cout << (double)(end - start) / CLOCKS_PER_SEC << "秒" << endl; 52 | 53 | 54 | return (EXIT_SUCCESS); 55 | } 56 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 17/1/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | int 7 | main (void) 8 | { 9 | const unsigned k_size = 64; 10 | const char key_char = '$'; 11 | unsigned char_cnt = 0; 12 | 13 | char line_txt[k_size]; 14 | while (cin.get(line_txt, k_size, key_char)) { 15 | char_cnt += strlen(line_txt); 16 | } 17 | cin.clear(); 18 | 19 | char ch; 20 | cin >> ch; 21 | cout << "第一个 " << ch << " 前出现了 " << char_cnt << " 个字符 (注,含换行符)" << endl; 22 | 23 | 24 | return (EXIT_SUCCESS); 25 | } 26 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 17/2/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | int 7 | main (int argc, char* argv[]) 8 | { 9 | if (argc != 2) { 10 | cerr << "格式:command file_name" << endl; 11 | return (EXIT_FAILURE); 12 | } 13 | 14 | ofstream file_out(argv[1]); 15 | string line; 16 | while (getline(cin, line)) { 17 | file_out << line << endl; 18 | } 19 | 20 | 21 | return (EXIT_SUCCESS); 22 | } 23 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 17/3/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | int 8 | main (int argc, char* argv[]) 9 | { 10 | if (argc != 3) { 11 | cerr << "错误!命令格式:command src_file_name dest_file_name" << endl; 12 | return (EXIT_FAILURE); 13 | } 14 | 15 | const string src_filename = argv[1]; 16 | const string dest_filename = argv[2]; 17 | if (src_filename == dest_filename) { 18 | cerr << "错误!源文件和目的文件不能重名" << endl; 19 | return (EXIT_FAILURE); 20 | } 21 | 22 | ifstream src_ifstream(src_filename); 23 | if (!src_ifstream) { 24 | cerr << "错误!" << src_filename << " 打开失败" << endl; 25 | return (EXIT_FAILURE); 26 | } 27 | 28 | ofstream dest_ofstream(dest_filename); 29 | if (!dest_ofstream) { 30 | cerr << "错误!" << dest_filename << " 打开失败" << endl; 31 | return (EXIT_FAILURE); 32 | } 33 | 34 | cout << "将 " << src_filename << " 拷贝至 " << dest_filename << " ... " << endl; 35 | string line; 36 | while (getline(src_ifstream, line)) { 37 | dest_ofstream << line << endl; 38 | } 39 | cout << "完成" << endl; 40 | 41 | 42 | return (EXIT_SUCCESS); 43 | } 44 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 17/4/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | int 8 | main (int argc, char* argv[]) 9 | { 10 | if (argc != 4) { 11 | cerr << "错误!命令格式:command src_filename_left src_filename_right dest_filename" << endl; 12 | return (EXIT_FAILURE); 13 | } 14 | 15 | const string src_filename_left = argv[1]; 16 | const string src_filename_right = argv[2]; 17 | const string dest_filename = argv[3]; 18 | if (src_filename_left == dest_filename || src_filename_right == dest_filename) { 19 | cerr << "错误!源文件和目的文件不能重名" << endl; 20 | return (EXIT_FAILURE); 21 | } 22 | 23 | ifstream src_ifstream_left(src_filename_left); 24 | if (!src_ifstream_left) { 25 | cerr << "错误!" << src_filename_left << " 打开失败" << endl; 26 | return (EXIT_FAILURE); 27 | } 28 | 29 | ifstream src_ifstream_right(src_filename_right); 30 | if (!src_ifstream_right) { 31 | cerr << "错误!" << src_filename_right << " 打开失败" << endl; 32 | return (EXIT_FAILURE); 33 | } 34 | 35 | ofstream dest_ofstream(dest_filename); 36 | if (!dest_ofstream) { 37 | cerr << "错误!" << dest_filename << " 打开失败" << endl; 38 | return (EXIT_FAILURE); 39 | } 40 | 41 | cout << "将 " << src_filename_left << " 与 " << src_filename_right << " 按行合并至 " << dest_filename << " ... " << endl; 42 | while (true) { 43 | string left_line, right_line; 44 | bool left_state = getline(src_ifstream_left, left_line); 45 | bool right_state = getline(src_ifstream_right, right_line); 46 | if (!left_state && !right_state) { 47 | break; 48 | } 49 | 50 | dest_ofstream << left_line + ' ' + right_line << endl; 51 | } 52 | cout << "完成" << endl; 53 | 54 | 55 | return (EXIT_SUCCESS); 56 | } 57 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 17/5/all: -------------------------------------------------------------------------------- 1 | ta ta 2 | la la 3 | piao piao 4 | yang yang 5 | ki ki 6 | john 7 | tong tong 8 | jia jia 9 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 17/5/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | 8 | using namespace std; 9 | 10 | int 11 | main (int argc, char* argv[]) 12 | { 13 | if (argc != 4) { 14 | cerr << "错误!命令格式:command mats_friends pats_friends all_friends" << endl; 15 | return (EXIT_FAILURE); 16 | } 17 | 18 | const string mats_friends_filename = argv[1]; 19 | const string pats_friends_filename = argv[2]; 20 | const string all_friends_filename = argv[3]; 21 | 22 | ifstream mats_friends_ifs(mats_friends_filename); 23 | if (!mats_friends_ifs) { 24 | cerr << "错误!" << mats_friends_filename << " 打开失败" << endl; 25 | return (EXIT_FAILURE); 26 | } 27 | 28 | ifstream pats_friends_ifs(pats_friends_filename); 29 | if (!pats_friends_ifs) { 30 | cerr << "错误!" << pats_friends_filename << " 打开失败" << endl; 31 | return (EXIT_FAILURE); 32 | } 33 | 34 | ofstream all_friends_ofs(all_friends_filename); 35 | if (!all_friends_ofs) { 36 | cerr << "错误!" << all_friends_filename << " 打开失败" << endl; 37 | return (EXIT_FAILURE); 38 | } 39 | 40 | string full_name; 41 | 42 | cout << "从文件 " << mats_friends_filename << " 中读取 Mat 的所有朋友:" << endl; 43 | unordered_set mat_friends; 44 | while (getline(mats_friends_ifs, full_name)) { 45 | mat_friends.insert(full_name); 46 | cout << full_name << endl; 47 | } 48 | cout << "完成。共计 " << mat_friends.size() << " 个" << endl << endl; 49 | 50 | cout << "从文件 " << pats_friends_filename << " 中读取 Pat 的所有朋友:" << endl; 51 | unordered_set pat_friends; 52 | while (getline(pats_friends_ifs, full_name)) { 53 | pat_friends.insert(full_name); 54 | cout << full_name << endl; 55 | } 56 | cout << "完成。共计 " << pat_friends.size() << " 个" << endl << endl; 57 | 58 | unordered_set all_friends(mat_friends.cbegin(), mat_friends.cend()); 59 | all_friends.insert(pat_friends.cbegin(), pat_friends.cend()); 60 | cout << "所有朋友如下:" << endl; 61 | copy(all_friends.cbegin(), all_friends.cend(), ostream_iterator(cout, "\n")); 62 | copy(all_friends.cbegin(), all_friends.cend(), ostream_iterator(all_friends_ofs, "\n")); 63 | cout << "已保存至文件 " << all_friends_filename << endl; 64 | cout << endl; 65 | 66 | 67 | 68 | return (EXIT_SUCCESS); 69 | } 70 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 17/5/mats: -------------------------------------------------------------------------------- 1 | yang yang 2 | ki ki 3 | tong tong 4 | ki ki 5 | jia jia 6 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 17/5/pats: -------------------------------------------------------------------------------- 1 | jia jia 2 | ta ta 3 | la la 4 | yang yang 5 | piao piao 6 | john 7 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 17/7/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | 8 | using namespace std; 9 | 10 | static void 11 | showStr (const string& str) 12 | { 13 | cout << str << endl; 14 | } 15 | 16 | class Storer 17 | { 18 | public: 19 | explicit Storer (ofstream& ofs) : ofs_(ofs) {} 20 | 21 | ofstream& operator() (const string& str) 22 | { 23 | auto len = str.size(); 24 | ofs_.write((char*)&len, sizeof(len)); 25 | ofs_.write(str.data(), (streamsize)len); 26 | 27 | return (ofs_); 28 | } 29 | 30 | 31 | private: 32 | ofstream& ofs_; 33 | }; 34 | 35 | static void 36 | getStrs (ifstream& ifs, vector& vistr) 37 | { 38 | while (true) { 39 | streamsize len; 40 | ifs.read((char*)&len, sizeof(len)); 41 | if (!ifs) { 42 | break; 43 | } 44 | 45 | char* p_char = new char [len + 1]; 46 | ifs.read(p_char, len); 47 | if (!ifs) { 48 | break; 49 | } 50 | p_char[len] = '\0'; 51 | vistr.push_back(p_char); 52 | delete [] p_char; 53 | } 54 | } 55 | 56 | int main() 57 | { 58 | vector vostr; 59 | string temp; 60 | 61 | // acquire strings 62 | cout << "Enter strings (empty line to quit):\n"; 63 | while (getline(cin,temp) && temp[0] != '\0') 64 | vostr.push_back(temp); 65 | cout << "Here is your input.\n"; 66 | for_each(vostr.begin(), vostr.end(), showStr); 67 | 68 | // store in a file 69 | ofstream fout("strings.dat", ios_base::out | ios_base::binary); 70 | for_each(vostr.begin(), vostr.end(), Storer(fout)); 71 | fout.close(); 72 | 73 | // recover file contents 74 | vector vistr; 75 | ifstream fin("strings.dat", ios_base::in | ios_base::binary); 76 | if (!fin.is_open()) 77 | { 78 | cerr << "Could not open file for input.\n"; 79 | exit(EXIT_FAILURE); 80 | } 81 | getStrs(fin, vistr); 82 | cout << "\nHere are the strings read from the file:\n"; 83 | for_each(vistr.begin(), vistr.end(), showStr); 84 | 85 | return 0; 86 | } 87 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 2/1/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int 4 | main (void) 5 | { 6 | 7 | using std::cout; 8 | using std::endl; 9 | 10 | cout << "我是yangyang.gnu, 定居成都。" << endl; 11 | 12 | cout << endl; 13 | return (0); 14 | } 15 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 2/2/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int 4 | main (void) 5 | { 6 | 7 | using std::cout; 8 | using std::cin; 9 | using std::endl; 10 | 11 | double furlongs; 12 | cout << "输入一段距离(单位弗隆):" << endl; 13 | cin >> furlongs; 14 | cout << furlongs << "(弗隆) 等于 " << furlongs * 220 << "(码)" << endl; 15 | 16 | cout << endl; 17 | return (0); 18 | } 19 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 2/3/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using std::cout; 4 | using std::cin; 5 | using std::endl; 6 | 7 | void 8 | print_mice (void) 9 | { 10 | cout << "Three blind mice" << endl; 11 | } 12 | 13 | void 14 | print_how (void) 15 | { 16 | cout << "See how they run" << endl; 17 | } 18 | 19 | int 20 | main (void) 21 | { 22 | 23 | print_mice(); 24 | print_mice(); 25 | print_how(); 26 | print_how(); 27 | 28 | cout << endl; 29 | return (0); 30 | } 31 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 2/4/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int 4 | main (void) 5 | { 6 | 7 | using std::cout; 8 | using std::cin; 9 | using std::endl; 10 | 11 | int age; 12 | cout << "Enter your age: "; 13 | cin >> age; 14 | cout << "Your age in months is " << age * 12 << endl; 15 | 16 | cout << endl; 17 | return (0); 18 | } 19 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 2/5/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | double 4 | to_fahrenheit (double celsius) 5 | { 6 | return (1.8 * celsius + 32.0); 7 | } 8 | 9 | int 10 | main (void) 11 | { 12 | using std::cout; 13 | using std::cin; 14 | using std::endl; 15 | 16 | double celsius; 17 | cout << "Please enter a Celsius value: "; 18 | cin >> celsius; 19 | cout << celsius << " degrees Celsius is " << to_fahrenheit(celsius) << " degrees Fahrenheit."; 20 | 21 | cout << endl; 22 | return (0); 23 | } 24 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 2/6/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | double 4 | to_astronomical (double lightYear) 5 | { 6 | return (lightYear * 63240); 7 | } 8 | 9 | int 10 | main (void) 11 | { 12 | 13 | using std::cout; 14 | using std::cin; 15 | using std::endl; 16 | 17 | double lightYear; 18 | cout << "Enter the number of light years: "; 19 | cin >> lightYear; 20 | cout << lightYear << " light years = " << to_astronomical(lightYear) << " astronomical units." << endl; 21 | 22 | cout << endl; 23 | return (0); 24 | } 25 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 2/7/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using std::cout; 4 | using std::cin; 5 | using std::endl; 6 | 7 | void 8 | show_time (int hour, int minute) 9 | { 10 | cout << "Time: " << hour << ":" << minute << endl; 11 | } 12 | 13 | int 14 | main (void) 15 | { 16 | int hour, minute; 17 | cout << "Enter the number of hours: "; 18 | cin >> hour; 19 | cout << "Enter the number of minutes: "; 20 | cin >> minute; 21 | show_time(hour, minute); 22 | 23 | cout << endl; 24 | return (0); 25 | } 26 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 3/1/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using std::cout; 4 | using std::cin; 5 | using std::endl; 6 | 7 | int 8 | main (void) 9 | { 10 | const int k_factorFeetToInch = 12; // 1英尺 = 12英寸 11 | int inches; 12 | cout << "输入身高,__英寸:"; 13 | cin >> inches; 14 | cout << "也就" << inches / k_factorFeetToInch << "英尺又" << inches % k_factorFeetToInch << "英寸"; 15 | 16 | cout << endl; 17 | return (0); 18 | } 19 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 3/2/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using std::cout; 4 | using std::cin; 5 | using std::endl; 6 | 7 | int 8 | main (void) 9 | { 10 | double height, weight, bmi; 11 | 12 | // 输入身高以英尺和英寸为单位 13 | int feet, inches; 14 | cout << "输入身高,__英尺又__英寸:"; 15 | cin >> feet >> inches; 16 | 17 | // 获得以英寸为单位的身高 18 | const int k_factorFeetToInches = 12; // 1英尺 = 12英寸 19 | height = feet * k_factorFeetToInches + inches; 20 | 21 | // 获得以米为单位的身高 22 | const double k_factorInchesToMeters = 0.0254; // 1英寸 = 0.0254米 23 | height = height * k_factorInchesToMeters; 24 | 25 | // 输入体重以磅为单位 26 | int pounds; 27 | cout << "输入以磅为单位的体重:"; 28 | cin >> pounds; 29 | 30 | // 获得以千克为单位的体重 31 | const double k_factorPoundsToKilograms = 1/2.2; // 1磅 = 1/2.2千克 32 | weight = pounds * k_factorPoundsToKilograms; 33 | 34 | // 计算BMI 35 | bmi = weight / (height * height); 36 | 37 | // 显示BMI 38 | cout << "BMI:" << bmi << endl; 39 | 40 | cout << endl; 41 | return (0); 42 | } 43 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 3/3/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using std::cout; 4 | using std::cin; 5 | using std::endl; 6 | 7 | int 8 | main (void) 9 | { 10 | int degrees, minutes, seconds; 11 | cout << "Enter a latitude in degrees, minutes, and seconds."; 12 | cout << "First, enter the degrees: "; 13 | cin >> degrees; 14 | cout << "Next, enter the minutes of arc: "; 15 | cin >> minutes; 16 | cout << "Finally, enter the seconds of arc: "; 17 | cin >> seconds; 18 | 19 | const int k_factor = 60; 20 | cout << degrees << " degrees, " << minutes << " minutes, " << seconds << " seconds = " 21 | << degrees + 1.0*minutes/k_factor + 1.0*seconds/k_factor/k_factor; 22 | 23 | cout << endl; 24 | return (0); 25 | } 26 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 3/4/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using std::cout; 4 | using std::cin; 5 | using std::endl; 6 | 7 | int 8 | main (void) 9 | { 10 | const long k_factorMinuteToSecond = 60; 11 | const long k_factorHourToMinute = 60; 12 | const long k_factorDayToHour = 24; 13 | 14 | cout << "Enter the number of seconds: "; 15 | 16 | long secondsTotal; 17 | cin >> secondsTotal; 18 | long seconds = secondsTotal % k_factorMinuteToSecond; 19 | 20 | long minutesTotal = secondsTotal / k_factorMinuteToSecond; 21 | long minutes = minutesTotal % k_factorHourToMinute; 22 | 23 | long hoursTotal = minutesTotal / k_factorHourToMinute; 24 | long hours = hoursTotal % k_factorDayToHour; 25 | 26 | long days = hoursTotal / k_factorDayToHour; 27 | 28 | cout << secondsTotal << " seconds = " << days << " days, " << hours << " hours, " << minutes << " minutes, " << seconds << " seconds"; 29 | 30 | cout << endl; 31 | return (0); 32 | } 33 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 3/5/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using std::cout; 4 | using std::cin; 5 | using std::endl; 6 | 7 | int 8 | main (void) 9 | { 10 | long long worldPopulation, usaPopulation; 11 | cout << "Enter the world's population: "; 12 | cin >> worldPopulation; 13 | cout << "Enter the population of the US: "; 14 | cin >> usaPopulation; 15 | cout << "The population of the US is " << 100.0 * usaPopulation / worldPopulation << "% of the world population."; 16 | 17 | cout << endl; 18 | return (0); 19 | } 20 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 3/6/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using std::cout; 4 | using std::cin; 5 | using std::endl; 6 | 7 | int 8 | main (void) 9 | { 10 | cout << "输入行驶公里数(公里)和耗油量(升):"; 11 | double distance, petrol; 12 | cin >> distance >> petrol; 13 | cout << "油耗为" << 100 * petrol / distance << "(升/100公里)"; 14 | 15 | cout << endl; 16 | return (0); 17 | } 18 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 3/7/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using std::cout; 4 | using std::cin; 5 | using std::endl; 6 | 7 | int 8 | main (void) 9 | { 10 | cout << "输入欧洲标准的油耗(升/100公里):"; 11 | double gasConsumptionInEuropean; 12 | cin >> gasConsumptionInEuropean; 13 | 14 | const double k_factorKmToMile = 0.6214; 15 | const double k_factorLiterToGallon = 1/3.875; 16 | cout << gasConsumptionInEuropean << "(升/100公里)=" << 100 * k_factorKmToMile / (gasConsumptionInEuropean * k_factorLiterToGallon) << "(英里/加仑)"; 17 | 18 | 19 | cout << endl; 20 | return (0); 21 | } 22 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 4/1/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using std::cout; 5 | using std::cin; 6 | using std::endl; 7 | using std::string; 8 | 9 | int 10 | main (void) 11 | { 12 | string strFirstname; 13 | cout << "What is your first name? "; 14 | getline(cin, strFirstname); 15 | 16 | string strLastname; 17 | cout << "What is your last name? "; 18 | cin >> strLastname; 19 | 20 | char chGrade; 21 | cout << "What letter grade do you deserve? "; 22 | cin >> chGrade; 23 | 24 | unsigned unAge; 25 | cout << "What is your age? "; 26 | cin >> unAge; 27 | 28 | cout << "Name: " << strLastname << ", " << strFirstname << endl; 29 | cout << "Grade: " << char(chGrade + 1) << endl; 30 | cout << "Age: " << unAge << endl; 31 | 32 | 33 | cout << endl; 34 | return (0); 35 | } 36 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 4/10/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using std::cout; 5 | using std::endl; 6 | using std::cin; 7 | using std::array; 8 | 9 | int 10 | main (void) 11 | { 12 | const unsigned k_times = 3; 13 | array dash_array; 14 | cout << "输入三次40米短跑成绩:"; 15 | cin >> dash_array[0] >> dash_array[1] >> dash_array[2]; 16 | 17 | cout << "共计输入" << k_times << "笔短跑成绩,平均分为" << (dash_array[0] + dash_array[1] + dash_array[2]) / 3 << endl; 18 | 19 | cout << endl; 20 | return (0); 21 | } 22 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 4/2/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using std::cout; 5 | using std::cin; 6 | using std::endl; 7 | using std::string; 8 | 9 | int 10 | main (void) 11 | { 12 | string strName; 13 | cout << "Enter your name:\n"; 14 | cin >> strName; 15 | 16 | string strDessert; 17 | cout << "Enter your favorite dessert:\n"; 18 | cin >> strDessert; 19 | 20 | cout << "I have some delicious " << strDessert; 21 | cout << " for you, " << strName << ".\n"; 22 | 23 | 24 | cout << endl; 25 | return (0); 26 | } 27 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 4/3/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using std::cout; 5 | using std::cin; 6 | using std::endl; 7 | 8 | int 9 | main (void) 10 | { 11 | const unsigned k_nameMaxLen = 64; 12 | 13 | char szFirstname[k_nameMaxLen]; 14 | cout << "Enter your first name: "; 15 | cin.getline(szFirstname, k_nameMaxLen); 16 | 17 | char szLastname[k_nameMaxLen]; 18 | cout << "Enter your last name: "; 19 | cin.getline(szLastname, k_nameMaxLen); 20 | 21 | char* const psz = new char [strlen(szFirstname) + strlen(szLastname) + 1]; 22 | strcpy(psz, szLastname); 23 | strcat(psz, ", "); 24 | strcat(psz, szFirstname); 25 | cout << "Here’s the information in a single string: " << psz; 26 | delete [] psz; 27 | 28 | 29 | cout << endl; 30 | return (0); 31 | } 32 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 4/4/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using std::cout; 5 | using std::cin; 6 | using std::endl; 7 | using std::string; 8 | 9 | int 10 | main (void) 11 | { 12 | string strFirstname; 13 | cout << "Enter your first name: "; 14 | cin >> strFirstname; 15 | 16 | string strLastname; 17 | cout << "Enter your last name: "; 18 | cin >> strLastname; 19 | 20 | string strInfo = strLastname + ", " + strFirstname; 21 | cout << "Here’s the information in a single string: " << strInfo; 22 | 23 | 24 | cout << endl; 25 | return (0); 26 | } 27 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 4/5/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using std::cout; 5 | using std::endl; 6 | using std::string; 7 | 8 | struct TCandyBar 9 | { 10 | string name; 11 | double weight; 12 | double calories; 13 | }; 14 | 15 | int 16 | main (void) 17 | { 18 | TCandyBar snack = {"Mocha Munch", 2.3, 350}; 19 | cout << snack.name << "\n" << snack.weight << "\n" << snack.calories << endl; 20 | 21 | cout << endl; 22 | return (0); 23 | } 24 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 4/6/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using std::cout; 5 | using std::endl; 6 | using std::string; 7 | 8 | struct TCandyBar 9 | { 10 | string name; 11 | double weight; 12 | double calories; 13 | }; 14 | 15 | int 16 | main (void) 17 | { 18 | TCandyBar snack[] = { {"Mocha Munch", 2.3, 350}, 19 | {"阿尔卑斯", 6.3, 310}, 20 | {"优の良品", 2.1, 291} }; 21 | cout << snack[0].name << "\t" << snack[0].weight << "\t" << snack[0].calories << endl; 22 | cout << snack[1].name << "\t" << snack[1].weight << "\t" << snack[1].calories << endl; 23 | cout << snack[2].name << "\t" << snack[2].weight << "\t" << snack[2].calories << endl; 24 | 25 | cout << endl; 26 | return (0); 27 | } 28 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 4/7/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using std::cout; 5 | using std::cin; 6 | using std::endl; 7 | using std::string; 8 | 9 | struct TPizza 10 | { 11 | string company_name; 12 | double diameter; 13 | double weight; 14 | }; 15 | 16 | int 17 | main (void) 18 | { 19 | TPizza pizza; 20 | 21 | cout << "输入披萨名:"; 22 | getline(cin, pizza.company_name); 23 | 24 | cout << "输入披萨直径(厘米):"; 25 | cin >> pizza.diameter; 26 | 27 | cout << "输入披萨重量(克):"; 28 | cin >> pizza.weight; 29 | 30 | cout << pizza.company_name << "公司出品直径为" << pizza.diameter << "厘米重量为" << pizza.weight << "克的披萨" << endl; 31 | 32 | cout << endl; 33 | return (0); 34 | } 35 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 4/8/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using std::cout; 5 | using std::cin; 6 | using std::endl; 7 | using std::string; 8 | 9 | struct TPizza 10 | { 11 | string company_name; 12 | double diameter; 13 | double weight; 14 | }; 15 | 16 | int 17 | main (void) 18 | { 19 | TPizza* p_pizza = new TPizza; 20 | 21 | cout << "输入披萨直径(厘米):"; 22 | cin >> p_pizza->diameter; // cin忽略输入流中的空白符(回车符、空格符、制表符),回车符仍保留在输入流中 23 | 24 | cout << "输入披萨名:"; 25 | cin.get(); // 提取先前留在输入流中的回车符,否则下面的getline()不会等待输入,而直接读取输入流中已有的回车符 26 | getline(cin, p_pizza->company_name); 27 | 28 | cout << "输入披萨重量(克):"; 29 | cin >> p_pizza->weight; 30 | 31 | cout << p_pizza->company_name << "公司出品直径为" << p_pizza->diameter << "厘米重量为" << p_pizza->weight << "克的披萨" << endl; 32 | 33 | delete p_pizza; 34 | p_pizza = NULL; 35 | 36 | cout << endl; 37 | return (0); 38 | } 39 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 4/9/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using std::cout; 5 | using std::endl; 6 | using std::string; 7 | 8 | struct TCandyBar 9 | { 10 | string name; 11 | double weight; 12 | double calories; 13 | }; 14 | 15 | int 16 | main (void) 17 | { 18 | const unsigned k_candybar_num = 3; 19 | TCandyBar* candybar_list = new TCandyBar [k_candybar_num]; 20 | 21 | candybar_list[0].name = "Mocha Munch"; 22 | candybar_list[0].weight = 2.3; 23 | candybar_list[0].calories = 350; 24 | 25 | candybar_list[1].name = "阿尔卑斯"; 26 | candybar_list[1].weight = 6.3; 27 | candybar_list[1].calories = 310; 28 | 29 | candybar_list[2].name = "优の良品"; 30 | candybar_list[2].weight = 2.1; 31 | candybar_list[2].calories = 291; 32 | 33 | cout << candybar_list[0].name << "\t" << candybar_list[0].weight << "\t" << candybar_list[0].calories << endl; 34 | cout << candybar_list[1].name << "\t" << candybar_list[1].weight << "\t" << candybar_list[1].calories << endl; 35 | cout << candybar_list[2].name << "\t" << candybar_list[2].weight << "\t" << candybar_list[2].calories << endl; 36 | 37 | delete [] candybar_list; 38 | candybar_list = NULL; 39 | 40 | cout << endl; 41 | return (0); 42 | } 43 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 5/1/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using std::cout; 4 | using std::endl; 5 | using std::cin; 6 | 7 | int 8 | main (void) 9 | { 10 | int nLowerBound, nUpperBound; 11 | cout << "输入区间:"; 12 | cin >> nLowerBound >> nUpperBound; 13 | 14 | int nSum = 0; 15 | for (int i = nLowerBound; i <= nUpperBound; ++i) { 16 | nSum += i; 17 | } 18 | 19 | cout << "[" << nLowerBound << ", " << nUpperBound << "]区间总和为" << nSum; 20 | 21 | cout << endl; 22 | return (0); 23 | } 24 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 5/10/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using std::cout; 4 | using std::endl; 5 | using std::cin; 6 | 7 | int 8 | main (void) 9 | { 10 | const char k_ch1 = '.'; 11 | const char k_ch2 = '*'; 12 | 13 | cout << "Enter number of rows: "; 14 | unsigned uRows; 15 | cin >> uRows; 16 | 17 | char* pCharLst = new char [uRows * uRows]; 18 | 19 | for (unsigned i = 0; i < uRows; ++i) { 20 | for (unsigned j = 0; j < uRows-i-1; ++j) { 21 | pCharLst[i*uRows + j] = k_ch1; 22 | } 23 | for (unsigned j = uRows-i-1; j < uRows; ++j) { 24 | pCharLst[i*uRows + j] = k_ch2; 25 | } 26 | } 27 | 28 | for (unsigned i = 0; i < uRows*uRows; ++i) { 29 | cout << pCharLst[i]; 30 | 31 | if (0 == (i+1) % uRows) { 32 | cout << endl; 33 | } 34 | } 35 | 36 | delete [] pCharLst; 37 | pCharLst = NULL; 38 | 39 | cout << endl; 40 | return (0); 41 | } 42 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 5/2/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using std::cout; 5 | using std::endl; 6 | using std::cin; 7 | using std::array; 8 | 9 | int 10 | main (void) 11 | { 12 | const unsigned k_uSize = 101; 13 | array factorials; 14 | factorials[1] = factorials[0] = 1.0L; 15 | 16 | for (unsigned i = 2; i < k_uSize; ++i) { 17 | factorials[i] = i * factorials[i-1]; 18 | } 19 | 20 | for (unsigned i = 0; i < k_uSize; ++i) { 21 | cout << i << "! = "<< factorials[i] << endl; 22 | } 23 | 24 | cout << endl; 25 | return (0); 26 | } 27 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 5/3/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using std::cout; 4 | using std::endl; 5 | using std::cin; 6 | 7 | int 8 | main (void) 9 | { 10 | const int k_nEndFlag = 0; 11 | int nSum = 0; 12 | int nTmp; 13 | cout << "输入数字:"; 14 | do { 15 | cin >> nTmp; 16 | nSum += nTmp; 17 | } while (k_nEndFlag != nTmp); 18 | 19 | cout << "总和为:" << nSum; 20 | 21 | 22 | cout << endl; 23 | return (0); 24 | } 25 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 5/4/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using std::cout; 4 | using std::endl; 5 | using std::cin; 6 | 7 | int 8 | main (void) 9 | { 10 | const double k_dSimpleInterest = 0.1; 11 | const double k_dCompoundInterest = 0.05; 12 | const double k_dDaphneBase = 100; 13 | const double k_dCleoBase = 100; 14 | 15 | unsigned uYears = 0; 16 | double dDaphneTotal = k_dDaphneBase, dCleoTotal = k_dCleoBase; 17 | do { 18 | dDaphneTotal += k_dDaphneBase * k_dSimpleInterest; 19 | dCleoTotal += dCleoTotal * k_dCompoundInterest; 20 | 21 | ++uYears; 22 | 23 | cout << uYears << ": " << dDaphneTotal << "\t" << dCleoTotal << endl; 24 | } while (dDaphneTotal >= dCleoTotal); 25 | 26 | cout << endl; 27 | cout << uYears << "年后," << "Cleo的财富将超过Daphne,前者将达到$" << dCleoTotal << "、后者$" << dDaphneTotal << endl; 28 | 29 | cout << endl; 30 | return (0); 31 | } 32 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 5/5/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using std::cout; 5 | using std::endl; 6 | using std::cin; 7 | using std::string; 8 | 9 | int 10 | main (void) 11 | { 12 | unsigned lstMonthlySales[12]; 13 | const string k_months[] = {"1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月"}; 14 | cout << "输入每月销售量。" << endl; 15 | for (int i = 0; i < 12; ++i) { 16 | cout << k_months[i] << ":"; 17 | cin >> lstMonthlySales[i]; 18 | } 19 | 20 | unsigned uSum = 0; 21 | for (int i = 0; i < 12; ++i) { 22 | uSum += lstMonthlySales[i]; 23 | } 24 | cout << "全年销售总量" << uSum << endl; 25 | 26 | 27 | cout << endl; 28 | return (0); 29 | } 30 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 5/6/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using std::cout; 5 | using std::endl; 6 | using std::cin; 7 | using std::string; 8 | 9 | int 10 | main (void) 11 | { 12 | unsigned lstMonthlySales[3][12]; 13 | const string k_months[] = {"1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月"}; 14 | for (int i = 0; i < 3; ++i) { 15 | cout << "输入第" << i + 1 << "年每月销售量。"<< endl; 16 | for (int j = 0; j < 12; ++j) { 17 | cout << k_months[j] << ":"; 18 | cin >> lstMonthlySales[i][j]; 19 | } 20 | cout << endl; 21 | } 22 | 23 | for (int i = 0; i < 3; ++i) { 24 | unsigned uSum = 0; 25 | for (int j = 0; j < 12; ++j) { 26 | uSum += lstMonthlySales[i][j]; 27 | } 28 | cout << "第" << i + 1 << "年销售总量" << uSum << endl; 29 | } 30 | 31 | 32 | cout << endl; 33 | return (0); 34 | } 35 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 5/7/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using std::cout; 5 | using std::endl; 6 | using std::cin; 7 | using std::string; 8 | 9 | struct TCar 10 | { 11 | string strMaker; 12 | unsigned uBulitYear; 13 | }; 14 | 15 | int 16 | main (void) 17 | { 18 | cout << "How many cars do you wish to catalog? "; 19 | unsigned uCatalogNum; 20 | cin >> uCatalogNum; 21 | cin.get(); 22 | 23 | TCar* pCarsLst = new TCar [uCatalogNum]; 24 | 25 | for (unsigned i = 0; i < uCatalogNum; ++i) { 26 | cout << "Car #" << i+1 << ": " << endl; 27 | 28 | cout << "Please enter the make: "; 29 | getline(cin, pCarsLst[i].strMaker); 30 | 31 | cout << "Please enter the year made: "; 32 | cin >> pCarsLst[i].uBulitYear; 33 | cin.get(); 34 | } 35 | 36 | cout << "Here is your collection: " << endl; 37 | for (unsigned i = 0; i < uCatalogNum; ++i) { 38 | cout << pCarsLst[i].uBulitYear << " " << pCarsLst[i].strMaker << endl; 39 | } 40 | 41 | delete [] pCarsLst; 42 | pCarsLst = NULL; 43 | 44 | 45 | 46 | cout << endl; 47 | return (0); 48 | } 49 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 5/8/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using std::cout; 5 | using std::endl; 6 | using std::cin; 7 | 8 | int 9 | main (void) 10 | { 11 | cout << "Enter words (to stop, type the word done): "; 12 | const char* const k_szDone = "done"; 13 | const unsigned k_uSize = 64; 14 | int cntWord = -1; 15 | char word[k_uSize]; 16 | do { 17 | ++cntWord; 18 | cin >> word; 19 | } while (strcmp(k_szDone, word)); 20 | cout << "You entered a total of " << cntWord << " words." << endl; 21 | 22 | cout << endl; 23 | return (0); 24 | } 25 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 5/9/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using std::cout; 5 | using std::endl; 6 | using std::cin; 7 | using std::string; 8 | 9 | int 10 | main (void) 11 | { 12 | cout << "Enter words (to stop, type the word done): "; 13 | const string k_strDone = "done"; 14 | int cntWord = -1; 15 | string strWord; 16 | do { 17 | ++cntWord; 18 | cin >> strWord; 19 | } while (k_strDone != strWord); 20 | cout << "You entered a total of " << cntWord << " words." << endl; 21 | 22 | cout << endl; 23 | return (0); 24 | } 25 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 6/1/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int 5 | main (void) 6 | { 7 | using namespace std; 8 | 9 | const char k_flagEnd = '@'; 10 | char ch; 11 | while (cin >> ch && k_flagEnd != ch) { 12 | if (isdigit(ch)) { 13 | continue; 14 | } 15 | 16 | if (islower(ch)) { 17 | ch = (char)toupper(ch); 18 | } else if (isupper(ch)) { 19 | ch = (char)tolower(ch); 20 | } else { 21 | ; // nop! 22 | } 23 | 24 | cout << ch; 25 | } 26 | 27 | cout << endl; 28 | return (0); 29 | } 30 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 6/2/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int 4 | main (void) 5 | { 6 | using namespace std; 7 | 8 | const unsigned k_size = 10; 9 | double arrDonation[k_size]; 10 | double dSum = 0; 11 | unsigned cntDonation = 0; 12 | while (cntDonation < k_size && cin >> arrDonation[cntDonation]) { 13 | dSum += arrDonation[cntDonation++]; 14 | } 15 | 16 | double dAverage = dSum / cntDonation; 17 | unsigned cntLargerAverage = 0; 18 | for (unsigned i = 0; i < k_size; ++i) { 19 | if (arrDonation[i] > dAverage) { 20 | ++cntLargerAverage; 21 | } 22 | } 23 | 24 | cout << "平均值为" << dAverage << ",超过平均值的有" << cntLargerAverage << "个。" << endl; 25 | 26 | 27 | cout << endl; 28 | return (0); 29 | } 30 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 6/3/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int 4 | main (void) 5 | { 6 | using namespace std; 7 | 8 | cout << "Please enter one of the following choices: " << endl; 9 | cout << "c) carnivore\t" << "p) pianist" << endl; 10 | cout << "t) tree\t\t" << "g) game" << endl; 11 | char ch; 12 | while (cin >> ch) { 13 | switch (ch) { 14 | case 'c': { 15 | cout << "A dog is a carnivore. " << endl; 16 | } 17 | break; 18 | 19 | case 'p': { 20 | cout << "Lang Lang is a pianist. " << endl; 21 | } 22 | break; 23 | 24 | case 't': { 25 | cout << "A maple is a tree." << endl; 26 | } 27 | break; 28 | 29 | case 'g': { 30 | cout << "Red alert is a game. " << endl; 31 | } 32 | break; 33 | 34 | default: 35 | cout << "Please enter a c, p, t, or g: "; 36 | break; 37 | } 38 | } 39 | 40 | 41 | cout << endl; 42 | return (0); 43 | } 44 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 6/4/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | 4 | const unsigned gk_size = 64; 5 | enum TPreference {FULLNAME, TITLE, BOPNAME}; 6 | struct TBop { 7 | char szFullname[gk_size]; // real name 8 | char szTitle[gk_size]; // job title 9 | char szBopname[gk_size]; // secret BOP name 10 | TPreference preference; 11 | }; 12 | 13 | int 14 | main (void) 15 | { 16 | using namespace std; 17 | 18 | TBop lstBops[] = { {"Yang Yang", "chinamobile", "yangyang.gnu", TITLE}, 19 | {"xiao wang", "microsoft", "xiaowang", BOPNAME}, 20 | {"xiao liu", "IBM", "xiaoliu", FULLNAME}, 21 | {"xiao zhang", "Huawei", "xiaozhang", TITLE} }; 22 | 23 | bool bDisplay = true; 24 | while (bDisplay) { 25 | cout << "Benevolent Order of Programmers Report" << endl; 26 | cout << "a. display by name" << "\t" << "b. display by title" << endl; 27 | cout << "c. display by bopname" << "\t" << "d. display by preference" << endl; 28 | cout << "q. quit" << endl; 29 | 30 | char chAction; 31 | if (!(cin >> chAction)) { 32 | bDisplay = false; 33 | break; 34 | } 35 | 36 | switch (chAction) { 37 | case 'a': { 38 | for (const auto& e : lstBops) { 39 | cout << e.szFullname << endl; 40 | }; 41 | } 42 | break; 43 | 44 | case 'b': { 45 | for (const auto& e : lstBops) { 46 | cout << e.szTitle << endl; 47 | }; 48 | } 49 | break; 50 | 51 | case 'c': { 52 | for (const auto& e : lstBops) { 53 | cout << e.szBopname << endl; 54 | }; 55 | } 56 | break; 57 | 58 | case 'd': { 59 | for (const auto& e : lstBops) { 60 | if (FULLNAME == e.preference) { 61 | cout << e.szFullname << endl; 62 | } else if (TITLE == e.preference) { 63 | cout << e.szTitle<< endl; 64 | } else if (BOPNAME == e.preference) { 65 | cout << e.szBopname<< endl; 66 | } else { 67 | ; 68 | } 69 | } 70 | } 71 | break; 72 | 73 | case 'q': { 74 | cout << "Bye! " << endl; 75 | bDisplay = false; 76 | } 77 | break; 78 | 79 | default: { 80 | cout << "Error! " << endl; 81 | } 82 | break; 83 | } 84 | } 85 | 86 | 87 | cout << endl; 88 | return (0); 89 | } 90 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 6/5/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int 4 | main (void) 5 | { 6 | using namespace std; 7 | 8 | // |-----|----------|--------------------|-----... 9 | // 0% (5K) 10% (1.5W) 15% (3.5W) 20% 10 | 11 | double tvarp; 12 | while (cin >> tvarp && tvarp >= 0) { 13 | double arrFourSection[4] = {5000, 10000, 20000}; 14 | 15 | if (tvarp <= 5000) { 16 | arrFourSection[0] = tvarp; 17 | arrFourSection[1] = arrFourSection[2] = arrFourSection[3] = 0; 18 | } else if ((tvarp -= 5000) <= 10000) { 19 | arrFourSection[1] = tvarp; 20 | arrFourSection[2] = arrFourSection[3] = 0; 21 | } else if ((tvarp -= 10000) <= 20000) { 22 | arrFourSection[2] = tvarp; 23 | arrFourSection[3] = 0; 24 | } else { 25 | arrFourSection[3] = tvarp - 20000; 26 | } 27 | 28 | cout << "税收明细如下:" 29 | << arrFourSection[0] << " * 0% + " << arrFourSection[1] << " * 10% + " 30 | << arrFourSection[2] << " * 15% + " << arrFourSection[3] << " * 20% " 31 | << " = " << arrFourSection[0] * 0 + arrFourSection[1] * 0.1 + arrFourSection[2] * 0.15 + arrFourSection[3] * 0.2 32 | << endl; 33 | } 34 | 35 | 36 | 37 | cout << endl; 38 | return (0); 39 | } 40 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 6/6/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | struct TDonor { 7 | string name; 8 | double amount; 9 | }; 10 | 11 | int 12 | main (void) 13 | { 14 | cout << "输入捐赠人数:"; 15 | unsigned num_donor; 16 | cin >> num_donor; 17 | TDonor* const p_donor = new TDonor [num_donor]; 18 | 19 | for (unsigned i = 0; i < num_donor; ++i) { 20 | cout << "输入捐赠人姓名:"; 21 | cin >> p_donor[i].name; 22 | cout << "输入捐赠金额:"; 23 | cin >> p_donor[i].amount; 24 | } 25 | 26 | cout << "荣誉捐赠者:" << endl; 27 | for (unsigned i = 0; i < num_donor; ++i) { 28 | if (p_donor[i].amount >= 10000) { 29 | cout << p_donor[i].name << endl; 30 | } 31 | } 32 | 33 | cout << "普通捐赠者:" << endl; 34 | for (unsigned i = 0; i < num_donor; ++i) { 35 | if (p_donor[i].amount < 10000) { 36 | cout << p_donor[i].name << endl; 37 | } 38 | } 39 | 40 | delete [] p_donor; 41 | 42 | 43 | cout << endl; 44 | return (0); 45 | } 46 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 6/7/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | 4 | int 5 | main (void) 6 | { 7 | using namespace std; 8 | 9 | unsigned cntVowels = 0, cntConsonants = 0, cntOthers = 0; 10 | 11 | cout << "输入单词,字母q结束:"; 12 | string word; 13 | while (cin >> word && "q" != word) { 14 | char& first_char = word[0]; 15 | if (!isalpha(first_char)) { 16 | ++cntOthers; 17 | } else if ( 'a' == first_char || 'A' == first_char || 18 | 'e' == first_char || 'E' == first_char || 19 | 'i' == first_char || 'I' == first_char || 20 | 'o' == first_char || 'O' == first_char || 21 | 'u' == first_char || 'U' == first_char ) { 22 | ++cntVowels; 23 | } else { 24 | ++cntConsonants; 25 | } 26 | } 27 | 28 | cout << "元音开头的单词" << cntVowels << "个、辅音单词" << cntConsonants << "个、其他" << cntOthers << "个" << endl; 29 | 30 | cout << endl; 31 | return (0); 32 | } 33 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 6/8/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | 6 | int 7 | main (void) 8 | { 9 | using namespace std; 10 | 11 | ifstream ifs("test_(for_linux).txt"); 12 | unsigned cntChars = 0; 13 | char ch; 14 | while (ifs.get(ch)) { 15 | ++cntChars; 16 | } 17 | --cntChars; // 抛掉读入的EOF符 18 | cout << cntChars << endl; 19 | 20 | cout << endl; 21 | 22 | system("pause"); 23 | return (0); 24 | } 25 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 6/8/main.cpp~: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | 5 | int 6 | main (void) 7 | { 8 | using namespace std; 9 | 10 | ifstream ifs("test.txt"); 11 | unsigned cntChars = 0; 12 | char ch; 13 | //while (ifs >> ch) { 14 | while (ifs.get(ch)) { 15 | ++cntChars; 16 | } 17 | --cntChars; // 抛掉读入的EOF符 18 | cout << cntChars << endl; 19 | 20 | cout << endl; 21 | return (0); 22 | } 23 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 6/8/test_(for_linux).txt: -------------------------------------------------------------------------------- 1 | 123 5 2 | 3 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 6/9/contributor_(for_linux).txt: -------------------------------------------------------------------------------- 1 | 4 2 | Sam Stone 3 | 2000 4 | Freida Flass 5 | 100500 6 | Tammy Tubbs 7 | 5000 8 | Rich Raptor 9 | 55000 10 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 6/9/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | struct TDonor { 8 | string name; 9 | double amount; 10 | }; 11 | 12 | int 13 | main (void) 14 | { 15 | ifstream ifs("C:\\Users\\Superone77\\Desktop\\6\\9\\donation.txt"); 16 | 17 | unsigned num_donor; 18 | ifs >> num_donor; 19 | TDonor* const p_donor = new TDonor [num_donor]; 20 | 21 | for (unsigned i = 0; i < num_donor; ++i) { 22 | ifs.get(); 23 | getline(ifs, p_donor[i].name); 24 | ifs >> p_donor[i].amount; 25 | } 26 | 27 | cout << "荣誉捐赠者:" << endl; 28 | for (unsigned i = 0; i < num_donor; ++i) { 29 | if (p_donor[i].amount >= 10000) { 30 | cout << p_donor[i].name << endl; 31 | } 32 | } 33 | 34 | cout << "普通捐赠者:" << endl; 35 | for (unsigned i = 0; i < num_donor; ++i) { 36 | if (p_donor[i].amount < 10000) { 37 | cout << p_donor[i].name << endl; 38 | } 39 | } 40 | 41 | delete [] p_donor; 42 | 43 | 44 | cout << endl; 45 | return (0); 46 | } 47 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 7/1/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | double 6 | calc_harmonic_mean (unsigned x, unsigned y) 7 | { 8 | return (2.0 * x * y / (x + y)); 9 | } 10 | 11 | int 12 | main (void) 13 | { 14 | while (true) { 15 | unsigned x, y; 16 | cout << "输入一对正整数,计算其调和平均数(0退出):"; 17 | cin >> x >> y; 18 | if (0 == x || 0 == y) { 19 | cout << "再会" << endl; 20 | break; 21 | } 22 | cout << "--> " << calc_harmonic_mean(x, y) << endl; 23 | } 24 | 25 | cout << endl; 26 | return (0); 27 | } 28 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 7/1/main.cpp~: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | double 6 | calcHarmonicMean (unsigned x, unsigned y) 7 | { 8 | return (2.0 * x * y / (x + y)); 9 | } 10 | 11 | int 12 | main (void) 13 | { 14 | while (true) { 15 | unsigned x, y; 16 | cout << "输入一对正整数,计算其调和平均数(0退出):"; 17 | cin >> x >> y; 18 | if (0 == x || 0 == y) { 19 | cout << "再会" << endl; 20 | break; 21 | } 22 | cout << "--> " << calcHarmonicMean(x, y) << endl; 23 | } 24 | 25 | cout << endl; 26 | return (0); 27 | } 28 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 7/10/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | typedef double (*TPfun) (double x, double y); 6 | 7 | void 8 | calculate (double x, double y, TPfun fun[], unsigned num_of_funs) 9 | { 10 | for (unsigned i = 0; i < num_of_funs; ++i) { 11 | cout << fun[i](x, y) << endl; 12 | } 13 | } 14 | 15 | double 16 | add (double x, double y) 17 | { 18 | cout << "加法操作结果:"; 19 | return (x + y); 20 | } 21 | 22 | double 23 | sub (double x, double y) 24 | { 25 | cout << "减法操作结果:"; 26 | return (x - y); 27 | } 28 | 29 | int 30 | main (void) 31 | { 32 | TPfun fun[] = {add, sub}; 33 | while (true) { 34 | cout << "输入两个数:"; 35 | double x, y; 36 | cin >> x >> y; 37 | if (!cin) { 38 | break; 39 | } 40 | calculate(x, y, fun, sizeof(fun)/sizeof(fun[0])); 41 | } 42 | 43 | cout << endl; 44 | return (0); 45 | } 46 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 7/2/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | unsigned 6 | input_golfscores (double arrGolfScores[], unsigned uSize) 7 | { 8 | double tmp; 9 | unsigned numGolfscores = 0; 10 | while (numGolfscores < uSize && cin >> tmp && -1 != tmp) { 11 | arrGolfScores[numGolfscores++] = tmp; 12 | } 13 | 14 | return (numGolfscores); 15 | } 16 | 17 | void 18 | display_golfscores (double arrGolfScores[], unsigned uSize) 19 | { 20 | for (unsigned i = 0; i < uSize; ++i) { 21 | cout << arrGolfScores[i] << ' '; 22 | } 23 | } 24 | 25 | double 26 | calc_average (double arrGolfScores[], unsigned uSize) 27 | { 28 | double sum = 0; 29 | for (unsigned i = 0; i < uSize; ++i) { 30 | sum += arrGolfScores[i]; 31 | } 32 | 33 | return (sum / uSize); 34 | } 35 | 36 | int 37 | main (void) 38 | { 39 | const unsigned k_size = 10; 40 | double arrGolfScores[k_size]; 41 | 42 | cout << "输入" << k_size << "个高尔夫成绩,-1可提前结束:"; 43 | unsigned numGolfscores = input_golfscores(arrGolfScores, k_size); 44 | cout << "高尔夫成绩明细如下:"; 45 | display_golfscores(arrGolfScores, numGolfscores); 46 | cout << endl; 47 | cout << "高尔夫成绩均值为:" << calc_average(arrGolfScores, numGolfscores) << endl; 48 | 49 | cout << endl; 50 | return (0); 51 | } 52 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 7/3/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | struct TBox 6 | { 7 | char szMaker[40]; 8 | float height; 9 | float width; 10 | float length; 11 | float volume; 12 | }; 13 | 14 | void 15 | display_box (TBox box) { 16 | cout << box.szMaker << '\t' << box.height << '\t' << box.width << '\t' << box.length; 17 | } 18 | 19 | float 20 | calc_box_volume (TBox* pBox) 21 | { 22 | return (pBox->volume = pBox->height * pBox->width * pBox->length); 23 | } 24 | 25 | int 26 | main (void) 27 | { 28 | TBox box = {"BigBro", 12, 8, 6, 0}; 29 | 30 | display_box(box); 31 | cout << endl; 32 | cout << "体积为:" << calc_box_volume(&box); 33 | 34 | cout << endl; 35 | return (0); 36 | } 37 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 7/4/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | long double 6 | calc_probability (unsigned numbers, unsigned picks) 7 | { 8 | long double probability = 1.0; 9 | while (picks > 0) { 10 | probability *= 1.0 * numbers / picks; 11 | --numbers; 12 | --picks; 13 | } 14 | 15 | return (probability); 16 | } 17 | 18 | int 19 | main (void) 20 | { 21 | long double probability = calc_probability(47, 5) * calc_probability(27, 1); 22 | cout << "你有" << fixed << probability << "分子一的几率中奖"; 23 | 24 | cout << endl; 25 | return (0); 26 | } 27 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 7/5/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | unsigned long long 6 | calc_factorial_less_equ_to_20 (unsigned long long n) 7 | { 8 | return ((0 == n) ? 1 : n * calc_factorial_less_equ_to_20(n-1)); 9 | } 10 | 11 | int 12 | main (void) 13 | { 14 | while (true) { 15 | cout << "输入一个不超过20的非负整数:"; 16 | unsigned long long n; 17 | cin >> n; 18 | if (!cin || n > 20) { // 采用递归实现的阶乘算法最多只能计算20以内的阶乘,否则将导致溢出 19 | break; 20 | } 21 | cout << n << "的阶乘为:" << calc_factorial_less_equ_to_20(n) << endl; 22 | } 23 | 24 | cout << endl; 25 | return (0); 26 | } 27 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 7/6/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | const int Max = 5; 4 | 5 | double* fill_array(double* pBeg, const double* pEnd) 6 | { 7 | using namespace std; 8 | double temp; 9 | int i = 0; 10 | while (pBeg < pEnd) 11 | { 12 | cout << "Enter value #" << i++ << ": "; 13 | cin >> temp; 14 | if (!cin) 15 | // bad input 16 | { 17 | cin.clear(); 18 | while (cin.get() != '\n') 19 | continue; 20 | cout << "Bad input; input process terminated.\n"; 21 | break; 22 | } 23 | else if (temp < 0) 24 | break; 25 | *pBeg = temp; 26 | ++pBeg; 27 | // signal to terminate 28 | } 29 | return pBeg; 30 | } 31 | 32 | // the following function can use, but not alter, 33 | // the array whose address is ar 34 | void show_array(const double* pBeg, const double* pEnd) 35 | { 36 | using namespace std; 37 | for (int i = 0; pBeg < pEnd; ++pBeg) 38 | { 39 | cout << "Property #" << (i + 1) << ": $"; 40 | cout << *pBeg << endl; 41 | } 42 | } 43 | 44 | // multiplies each element of ar[] by r 45 | void revalue(double r, double* pBeg, const double* pEnd) 46 | { 47 | while (pBeg < pEnd) 48 | { 49 | *pBeg *= r; 50 | ++pBeg; 51 | } 52 | } 53 | 54 | 55 | int main() 56 | { 57 | using namespace std; 58 | double properties[Max]; 59 | double* pArrEnd = fill_array(properties, properties+Max); 60 | show_array(properties, pArrEnd); 61 | if (pArrEnd - properties > 0) 62 | { 63 | cout << "Enter revaluation factor: "; 64 | double factor; 65 | while (!(cin >> factor)) 66 | // bad input 67 | { 68 | cin.clear(); 69 | while (cin.get() != '\n') 70 | continue; 71 | cout << "Bad input; Please enter a number: "; 72 | } 73 | revalue(factor, properties, pArrEnd); 74 | show_array(properties, pArrEnd); 75 | } 76 | cout << "Done.\n"; 77 | cin.get(); 78 | cin.get(); 79 | return 0; 80 | } 81 | 82 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 7/7/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | const int Max = 5; 4 | 5 | int fill_array(double* pBeg, const double* pEnd) 6 | { 7 | using namespace std; 8 | double temp; 9 | int i = 0; 10 | while (pBeg < pEnd) 11 | { 12 | cout << "Enter value #" << i++ << ": "; 13 | cin >> temp; 14 | if (!cin) 15 | // bad input 16 | { 17 | cin.clear(); 18 | while (cin.get() != '\n') 19 | continue; 20 | cout << "Bad input; input process terminated.\n"; 21 | break; 22 | } 23 | else if (temp < 0) 24 | break; 25 | *pBeg = temp; 26 | ++pBeg; 27 | // signal to terminate 28 | } 29 | return i; 30 | } 31 | 32 | // the following function can use, but not alter, 33 | // the array whose address is ar 34 | void show_array(const double* pBeg, const double* pEnd) 35 | { 36 | using namespace std; 37 | for (int i = 0; pBeg < pEnd; ++pBeg) 38 | { 39 | cout << "Property #" << (i + 1) << ": $"; 40 | cout << *pBeg << endl; 41 | } 42 | } 43 | 44 | // multiplies each element of ar[] by r 45 | void revalue(double r, double* pBeg, const double* pEnd) 46 | { 47 | while (pBeg < pEnd) 48 | { 49 | *pBeg *= r; 50 | ++pBeg; 51 | } 52 | } 53 | 54 | 55 | int main() 56 | { 57 | using namespace std; 58 | double properties[Max]; 59 | int size = fill_array(properties, properties+Max); 60 | show_array(properties, properties+size); 61 | if (size > 0) 62 | { 63 | cout << "Enter revaluation factor: "; 64 | double factor; 65 | while (!(cin >> factor)) 66 | // bad input 67 | { 68 | cin.clear(); 69 | while (cin.get() != '\n') 70 | continue; 71 | cout << "Bad input; Please enter a number: "; 72 | } 73 | revalue(factor, properties, properties+size); 74 | show_array(properties, properties+size); 75 | } 76 | cout << "Done.\n"; 77 | cin.get(); 78 | cin.get(); 79 | return 0; 80 | } 81 | 82 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 7/8/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | PROJECT(main) 2 | SET(SRC_LIST main.cpp) 3 | SET(CMAKE_CXX_COMPILER "clang++") 4 | SET(CMAKE_CXX_FLAGS "-std=c++11 -Weverything -O3") 5 | SET(CMAKE_BUILD_TYPE Release) 6 | ADD_EXECUTABLE(main ${SRC_LIST}) 7 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 7/8/a/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | // constant data 5 | const int Seasons = 4; 6 | const char* Snames[] = {"Spring", "Summer", "Fall", "Winter"}; 7 | 8 | void fill(double* pa) 9 | { 10 | using namespace std; 11 | for (int i = 0; i < Seasons; i++) 12 | { 13 | cout << "Enter " << Snames[i] << " expenses: "; 14 | cin >> pa[i]; 15 | } 16 | } 17 | 18 | void show(double da[]) 19 | { 20 | using namespace std; 21 | double total = 0.0; 22 | cout << "\nEXPENSES\n"; 23 | for (int i = 0; i < Seasons; i++) 24 | { 25 | cout << Snames[i] << ": $" << da[i] << endl; 26 | total += da[i]; 27 | } 28 | cout << "Total Expenses: $" << total << endl; 29 | } 30 | 31 | int main() 32 | { 33 | double expenses[Seasons]; 34 | fill(expenses); 35 | show(expenses); 36 | return 0; 37 | } 38 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 7/8/b/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | // constant data 5 | const int Seasons = 4; 6 | const char* Snames[] = {"Spring", "Summer", "Fall", "Winter"}; 7 | 8 | struct TData 9 | { 10 | double arr[Seasons]; 11 | }; 12 | 13 | 14 | void fill(TData* pData) 15 | { 16 | using namespace std; 17 | for (int i = 0; i < Seasons; i++) 18 | { 19 | cout << "Enter " << Snames[i] << " expenses: "; 20 | cin >> pData->arr[i]; 21 | } 22 | } 23 | 24 | void show(TData data) 25 | { 26 | using namespace std; 27 | double total = 0.0; 28 | cout << "\nEXPENSES\n"; 29 | for (int i = 0; i < Seasons; i++) 30 | { 31 | cout << Snames[i] << ": $" << data.arr[i] << endl; 32 | total += data.arr[i]; 33 | } 34 | cout << "Total Expenses: $" << total << endl; 35 | } 36 | 37 | int main() 38 | { 39 | TData expenses; 40 | fill(&expenses); 41 | show(expenses); 42 | return 0; 43 | } 44 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 7/9/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | PROJECT(main) 2 | SET(SRC_LIST main.cpp) 3 | SET(CMAKE_CXX_COMPILER "clang++") 4 | SET(CMAKE_CXX_FLAGS "-std=c++11 -Weverything -O3") 5 | SET(CMAKE_BUILD_TYPE Release) 6 | ADD_EXECUTABLE(main ${SRC_LIST}) 7 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 8/1/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | unsigned k_times = 0; 6 | void 7 | print_times (const char* szTmp, int flag = 0) 8 | { 9 | ++k_times; 10 | unsigned uPrintfTimes = (0 == flag) ? 1 : k_times; 11 | cout << ">>>>" << endl; 12 | for (unsigned i = 0; i < uPrintfTimes; ++i) { 13 | cout << szTmp << endl; 14 | } 15 | cout << "<<<<" << endl; 16 | cout << "-----------------" << endl; 17 | } 18 | 19 | int 20 | main (void) 21 | { 22 | const char* szTxt = "hi, yangyang.gnu"; 23 | print_times(szTxt, 8); 24 | print_times(szTxt); 25 | print_times(szTxt, -1); 26 | print_times(szTxt); 27 | print_times(szTxt, 256); 28 | 29 | cout << endl; 30 | return (0); 31 | } 32 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 8/2/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | struct TCandyBar 6 | { 7 | string strBrand; 8 | double weight; 9 | int calories; 10 | }; 11 | 12 | void 13 | set_candybar (TCandyBar& candbar, const char* strBrand = "Millennium Munch", double weight = 2.85, int calories = 350) 14 | { 15 | candbar.strBrand = strBrand; 16 | candbar.weight = weight; 17 | candbar.calories = calories; 18 | } 19 | 20 | void 21 | show_candybar (const TCandyBar& candbar) 22 | { 23 | cout << candbar.strBrand << '\t' << candbar.weight << '\t' << candbar.calories << endl; 24 | } 25 | 26 | int 27 | main (void) 28 | { 29 | TCandyBar candbar1, candbar2; 30 | set_candybar(candbar1); 31 | show_candybar(candbar1); 32 | set_candybar(candbar2, "yang yang", 3.11, 256); 33 | show_candybar(candbar2); 34 | 35 | cout << endl; 36 | return (0); 37 | } 38 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 8/3/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | string& 7 | str_to_upper (string& str) 8 | { 9 | for (auto& e : str) { 10 | e = (char)toupper(e); 11 | } 12 | 13 | return (str); 14 | } 15 | 16 | int 17 | main (void) 18 | { 19 | while (true) { 20 | cout << "Enter a string (q to quit): "; 21 | 22 | string strInput; 23 | getline(cin, strInput); 24 | if (!cin || "q" == strInput || "Q" == strInput) { 25 | break; 26 | } 27 | 28 | cout << str_to_upper(strInput) << endl; 29 | } 30 | 31 | 32 | cout << endl; 33 | return (0); 34 | } 35 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 8/4/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | struct stringy { 7 | char * str; 8 | int ct; 9 | }; 10 | 11 | void 12 | set (stringy& stry, const char* szTxt) 13 | { 14 | stry.ct = (int)strlen(szTxt); 15 | stry.str = new char [stry.ct + 1]; 16 | strcpy(stry.str, szTxt); 17 | } 18 | 19 | void 20 | show (const char* szTxt, unsigned times = 1) 21 | { 22 | for (unsigned i = 0; i < times; ++i) { 23 | cout << szTxt << endl; 24 | } 25 | } 26 | 27 | void 28 | show (const stringy& stry, unsigned times = 1) 29 | { 30 | for (unsigned i = 0; i < times; ++i) { 31 | cout << stry.str << endl; 32 | } 33 | } 34 | 35 | void 36 | destroy (stringy& stry) 37 | { 38 | delete [] stry.str; 39 | stry.str = NULL; 40 | } 41 | 42 | int main() 43 | { 44 | stringy beany; 45 | char testing[] = "Reality isn't what it used to be."; 46 | set(beany, testing); 47 | 48 | show(beany); 49 | show(beany, 2); 50 | destroy(beany); 51 | 52 | testing[0] = 'D'; 53 | testing[1] = 'u'; 54 | show(testing); 55 | show(testing, 3); 56 | show("Done!"); 57 | 58 | return 0; 59 | // prints member string once 60 | // prints member string twice 61 | // prints testing string once 62 | // prints testing string thrice 63 | } 64 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 8/5/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | template 7 | const T& 8 | max5 (const array& arr) 9 | { 10 | unsigned idxMax = 0; 11 | for (unsigned i = 0; i < 5; ++i) { 12 | if (arr[i] > arr[idxMax]) { 13 | idxMax = i; 14 | } 15 | } 16 | 17 | return (arr[idxMax]); 18 | } 19 | 20 | int 21 | main (void) 22 | { 23 | array iArray = {{32, -1, 99, 256, 9}}; 24 | for (const auto& e : iArray) { 25 | cout << e << ' '; 26 | } 27 | cout << " ----max: " << max5(iArray) << endl; 28 | 29 | array dArray = {{-3.2, 221.22, 9.9, 0, 1}}; 30 | for (const auto& e : dArray) { 31 | cout << e << ' '; 32 | } 33 | cout << " ----max: " << max5(dArray); 34 | 35 | 36 | cout << endl; 37 | return 0; 38 | } 39 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 8/6/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | // 模板函数 7 | template 8 | T maxn (T arr[], unsigned n) 9 | { 10 | unsigned idxMax = 0; 11 | for (unsigned i = 0; i < n; ++i) { 12 | if (arr[i] > arr[idxMax]) { 13 | idxMax = i; 14 | } 15 | } 16 | 17 | return (arr[idxMax]); 18 | } 19 | 20 | 21 | // 模板具体化 (要使用模板具体化的需要把模板函数和具体化函数的声明一致。否则编译报错:没有与指定类型匹配的模板函数。 22 | // 这里修改了模板函数声明【原始声明为 template const T& maxn (const T arr[], unsigned n))】 23 | // 这里猜测不匹配的原因是:模板具体化函数中的const char * 整个被认为是模板函数中的T,所以当在模板函数中再对T进行const限定时,就会认为非模板函数中为非const类型,进而出现不匹配。 24 | // 即使在模板具体化maxn后的<>中指明类型T仅为char *【template <> const char *maxn】,仍是会报不匹配错误。 25 | // 所以,目前这种写法是将const char *整体作为T,编译通过,运行结果也正确。暂时只理解到这种程度,欢迎大家指正。Thanks♪(・ω・)ノ 20200717 26 | template <> const char* maxn(const char *arr[], unsigned n) 27 | { 28 | unsigned idxMax = 0; 29 | if ( n > 0 ) { 30 | for ( unsigned i=0; i strlen(arr[idxMax]) ) { 32 | idxMax = i; 33 | } 34 | } 35 | } 36 | return arr[idxMax]; 37 | } 38 | 39 | 40 | int 41 | main (void) 42 | { 43 | int iArray[] = {32, -1, 99, 0, 256, 9}; 44 | for (const auto& e : iArray) { 45 | cout << e << ' '; 46 | } 47 | cout << " ----max: " << maxn(iArray, sizeof(iArray)/sizeof(iArray[0])) << endl; 48 | 49 | double dArray[] = {-3.2, 221.22, 9.9, 0, 1}; 50 | for (const auto& e : dArray) { 51 | cout << e << ' '; 52 | } 53 | cout << " ----max: " << maxn(dArray, sizeof(dArray)/sizeof(dArray[0])) << endl; 54 | 55 | const char* szArray[] = { "aa aa", 56 | "dddddddddddd", 57 | "", 58 | "fffffff ffff", 59 | "kk kk", 60 | }; 61 | for (const auto& e : szArray) { 62 | cout << '\"' << e << '\"' << ' '; 63 | } 64 | cout << " ----max: " << '\"' << maxn(szArray, sizeof(szArray)/sizeof(szArray[0])) << '\"' << endl; 65 | 66 | 67 | cout << endl; 68 | return 0; 69 | } 70 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 8/7/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | struct debts 4 | { 5 | char name[50]; 6 | double amount; 7 | }; 8 | 9 | template 10 | double SumArray(T arr[], int n) 11 | { 12 | using namespace std; 13 | cout << "template A\n"; 14 | double sum = 0; 15 | for (int i = 0; i < n; i++) 16 | sum += arr[i]; 17 | 18 | return (sum); 19 | } 20 | 21 | template 22 | double SumArray(T * arr[], int n) 23 | { 24 | using namespace std; 25 | cout << "template B\n"; 26 | double sum = 0; 27 | for (int i = 0; i < n; i++) 28 | sum += *arr[i]; 29 | 30 | return (sum); 31 | } 32 | 33 | int main() 34 | { 35 | using namespace std; 36 | int things[6] = {13, 31, 103, 301, 310, 130}; 37 | struct debts mr_E[3] = { {"Ima Wolfe", 2400.0}, 38 | {"Ura Foxe", 1300.0}, 39 | {"Iby Stout", 1800.0} }; 40 | double * pd[3]; 41 | for (int i = 0; i < 3; i++) 42 | pd[i] = &mr_E[i].amount; 43 | cout << "the total number of Mr. E's things:\n" << SumArray(things, 6) << endl; 44 | cout << "the sum of Mr. E's all debts:\n" << SumArray(pd, 3); 45 | 46 | return 0; 47 | } 48 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 9/1/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | PROJECT(main) 2 | SET(SRC_LIST main.cpp golf.cpp) 3 | SET(CMAKE_CXX_COMPILER "clang++") 4 | SET(CMAKE_CXX_FLAGS "-std=c++11 -Werror -Weverything -Wno-c++98-compat -Wc++98-compat-pedantic -Wno-float-equal -Wno-global-constructors -Wno-exit-time-destructors -Wno-missing-prototypes -O3") 5 | SET(CMAKE_BUILD_TYPE Release) 6 | ADD_EXECUTABLE(main ${SRC_LIST}) 7 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 9/1/golf.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include "golf.h" 4 | 5 | using std::cin; 6 | using std::cout; 7 | using std::endl; 8 | using std::string; 9 | 10 | void 11 | setgolf (golf & g, const char * name, int hc) 12 | { 13 | strcpy(g.fullname, name); 14 | g.handicap = hc; 15 | } 16 | 17 | int 18 | setgolf (golf & g) 19 | { 20 | cout << "输入姓名:"; 21 | string strTmp; 22 | getline(cin, strTmp); 23 | if ("" == strTmp) { 24 | return (0); 25 | } 26 | strcpy(g.fullname, strTmp.c_str()); 27 | 28 | cout << "输入差点:"; 29 | int n; 30 | cin >> n; 31 | cin.get(); 32 | if (!n) { 33 | return (0); 34 | } 35 | g.handicap = n; 36 | 37 | return (1); 38 | } 39 | 40 | void 41 | handicap(golf & g, int hc) 42 | { 43 | g.handicap = hc; 44 | } 45 | 46 | void 47 | showgolf(const golf & g) 48 | { 49 | cout << g.fullname << '\t' << g.handicap; 50 | } 51 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 9/1/golf.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | const int Len = 40; 4 | struct golf 5 | { 6 | char fullname[Len]; 7 | int handicap; 8 | }; 9 | 10 | // non-interactive version: 11 | // function sets golf structure to provided name, handicap 12 | // using values passed as arguments to the function 13 | void setgolf(golf & g, const char * name, int hc); 14 | 15 | // interactive version: 16 | // function solicits name and handicap from user 17 | // and sets the members of g to the values entered 18 | // returns 1 if name is entered, 0 if name is empty string 19 | int setgolf(golf & g); 20 | 21 | // function resets handicap to new value 22 | void handicap(golf & g, int hc); 23 | 24 | // function displays contents of golf structure 25 | void showgolf(const golf & g); 26 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 9/1/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include "golf.h" 4 | 5 | using namespace std; 6 | 7 | 8 | int 9 | main (void) 10 | { 11 | const unsigned k_size = 4; 12 | golf golfers[k_size]; 13 | unsigned numGolfers = 0; 14 | while (numGolfers < k_size && setgolf(golfers[numGolfers])) { 15 | ++numGolfers; 16 | } 17 | 18 | for (unsigned i = 0; i < numGolfers; ++i) { 19 | showgolf(golfers[i]); 20 | cout << endl; 21 | } 22 | 23 | 24 | cout << endl; 25 | return (0); 26 | } 27 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 9/2/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main() 5 | { 6 | using namespace std; 7 | string input; 8 | unsigned total = 0; 9 | cout << "Enter a line:\n"; 10 | getline(cin, input); 11 | while (cin && "" != input) 12 | { 13 | cout << "\"" << input <<"\" contains "; 14 | cout << input.size() << " characters\n"; 15 | total += input.size(); 16 | cout << total << " characters total\n"; 17 | 18 | cout << "Enter next line (empty line to quit):\n"; 19 | getline(cin, input); 20 | } 21 | cout << "Bye\n"; 22 | return 0; 23 | } 24 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 9/3/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | struct TChaff 7 | { 8 | char szDross[20]; 9 | int slag; 10 | }; 11 | 12 | char g_buffer[1024]; 13 | 14 | int 15 | main (void) 16 | { 17 | TChaff* pChaff = new (g_buffer) TChaff [2]; 18 | 19 | strcpy(pChaff[0].szDross, "foo"); 20 | pChaff[0].slag = 2; 21 | 22 | strcpy(pChaff[1].szDross, "bar"); 23 | pChaff[1].slag = 8; 24 | 25 | for (unsigned i = 0; i < 2; ++i) { 26 | cout << pChaff[i].szDross << '\t' << pChaff[i].slag << endl; 27 | } 28 | 29 | 30 | cout << endl; 31 | return (0); 32 | } 33 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 9/4/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | PROJECT(main) 2 | SET(SRC_LIST main.cpp Sales.cpp) 3 | SET(CMAKE_CXX_COMPILER "clang++") 4 | SET(CMAKE_CXX_FLAGS "-std=c++11 -Werror -Weverything -Wno-float-equal -Wno-c++98-compat -Wno-c++98-compat-pedantic -Wno-global-constructors -Wno-exit-time-destructors -Wno-missing-prototypes -Wno-padded -O3") 5 | SET(CMAKE_BUILD_TYPE Release) 6 | ADD_EXECUTABLE(main ${SRC_LIST}) 7 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 9/4/Sales.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "Sales.h" 3 | 4 | namespace SALES 5 | { 6 | using std::cin; 7 | using std::cout; 8 | using std::endl; 9 | using std::string; 10 | 11 | static double 12 | calcAverage (double arr[], unsigned arrSize) 13 | { 14 | double sum = 0; 15 | for (unsigned i = 0; i < arrSize; ++i) { 16 | sum += arr[i]; 17 | } 18 | 19 | return (sum / arrSize); 20 | } 21 | 22 | static double 23 | calcMax (double arr[], unsigned arrSize) 24 | { 25 | unsigned idxMax = 0; 26 | for (unsigned i = 0; i < arrSize; ++i) { 27 | if (arr[i] > arr[idxMax]) { 28 | idxMax = i; 29 | } 30 | } 31 | 32 | return (arr[idxMax]); 33 | } 34 | 35 | static double 36 | calcMin (double arr[], unsigned arrSize) 37 | { 38 | unsigned idxMin = 0; 39 | for (unsigned i = 0; i < arrSize; ++i) { 40 | if (arr[i] < arr[idxMin]) { 41 | idxMin = i; 42 | } 43 | } 44 | 45 | return (arr[idxMin]); 46 | } 47 | 48 | void 49 | setSales (Sales & s, const double ar[], int n) 50 | { 51 | unsigned times = n < QUARTERS ? (unsigned)n : QUARTERS; 52 | for (unsigned i = 0; i < times; ++i) { 53 | s.sales[i] = ar[i]; 54 | } 55 | for (unsigned i = times; i < QUARTERS; ++i) { 56 | s.sales[i] = 0; 57 | } 58 | 59 | s.average = calcAverage(s.sales, times); 60 | s.max = calcMax(s.sales, times); 61 | s.min = calcMin(s.sales, times); 62 | } 63 | 64 | void 65 | setSales(Sales & s) 66 | { 67 | cout << "输入" << QUARTERS << "个销售记录:"; 68 | unsigned times = QUARTERS; 69 | double arr[QUARTERS] = {0}; 70 | for (unsigned i = 0; i < QUARTERS; ++i) { 71 | cin >> arr[i]; 72 | if (!cin) { 73 | times = i; 74 | break; 75 | } 76 | } 77 | 78 | setSales(s, arr, QUARTERS); 79 | 80 | s.average = calcAverage(s.sales, times); 81 | s.max = calcMax(s.sales, times); 82 | s.min = calcMin(s.sales, times); 83 | } 84 | 85 | void 86 | showSales (const Sales & s) 87 | { 88 | cout << "sales: "; 89 | for (const auto& e : s.sales) { 90 | cout << e << ' '; 91 | } 92 | cout << endl; 93 | cout << "average: " << s.average << endl; 94 | cout << "max: " << s.max << endl; 95 | cout << "min: " << s.min << endl; 96 | } 97 | } 98 | 99 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 9/4/Sales.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | namespace SALES 3 | { 4 | const int QUARTERS = 4; 5 | 6 | struct Sales 7 | { 8 | double sales[QUARTERS]; 9 | double average; 10 | double max; 11 | double min; 12 | }; 13 | 14 | // copies the lesser of 4 or n items from the array ar 15 | // to the sales member of s and computes and stores the 16 | // average, maximum, and minimum values of the entered items; 17 | // remaining elements of sales, if any, set to 0 18 | void setSales(Sales & s, const double ar[], int n); 19 | 20 | // gathers sales for 4 quarters interactively, stores them 21 | // in the sales member of s and computes and stores the 22 | // average, maximum, and minimum values 23 | void setSales(Sales & s); 24 | 25 | // display all information in structure s 26 | void showSales(const Sales & s); 27 | } 28 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/chapter 9/4/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "Sales.h" 3 | 4 | using namespace std; 5 | 6 | 7 | int 8 | main (void) 9 | { 10 | using namespace SALES; 11 | 12 | Sales salesBook; 13 | double salesLst[] = {12.2, 11.16, 10.61, 16.24, 11.53}; 14 | setSales(salesBook, salesLst, sizeof(salesLst)/sizeof(salesLst[0])); 15 | showSales(salesBook); 16 | 17 | Sales salesPen; 18 | setSales(salesPen); 19 | showSales(salesPen); 20 | 21 | 22 | cout << endl; 23 | return (0); 24 | } 25 | -------------------------------------------------------------------------------- /cpp_primer_plus_code/《C++ Primer Plus(第6版)中文版》习题答案/readme: -------------------------------------------------------------------------------- 1 | 《C++ Primer Plus(第6版)中文版》习题答案,任何问题请联系 yangyang.gnu@gmail.com 2 | 3 | 说明: 4 | 1、目录结构:每个习题对应一个以其编号命名的目录; 5 | 2、构建系统:所有源码采用cmake构建(习题目录中有CMakeLists.txt的直接使用,没有的使用根目录下的CMakeLists.txt),编译器clang v3.1(支持 C++11)。构建方式: 6 | cmake . 7 | make 8 | 3、超前知识:所有答案(代码)仅使用已出现的知识点,这将导致: 9 | 1)部分代码存在实现别扭、效率低下的可能; 10 | 2)部分代码实现不严谨,甚至存在BUG的可能; 11 | 4、命名习惯:部分标识符可能与习题规定的不同,我遵循自己的命名习惯。如,第四章的习题5要求结构名为CandyBar,但我习惯在类型前添加T前缀,所以有别于习题而采用TCandyBar; 12 | -------------------------------------------------------------------------------- /imooc_code/data_structure/List/Coordinate.cpp: -------------------------------------------------------------------------------- 1 | #include"Coordinate.h" 2 | #include 3 | using namespace std; 4 | 5 | Coordinate::Coordinate(int x, int y) 6 | { 7 | m_iX = x; 8 | m_iY = y; 9 | } 10 | 11 | void 12 | Coordinate::printCoordinate() 13 | { 14 | cout << "(" << m_iX << "," << m_iY << ")" << endl; 15 | } 16 | 17 | ostream &operator<<(ostream &out, Coordinate &coor) 18 | { 19 | out << "(" << coor.m_iX << "," << coor.m_iY << ")" << endl; 20 | return out; 21 | } 22 | 23 | bool Coordinate::operator==(Coordinate &coor) 24 | { 25 | if (this->m_iX == coor.m_iX && this->m_iY == coor.m_iY) 26 | { 27 | return true; 28 | } 29 | 30 | return false; 31 | } -------------------------------------------------------------------------------- /imooc_code/data_structure/List/Coordinate.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | 5 | using namespace std; 6 | 7 | class Coordinate 8 | { 9 | friend ostream &operator<<(ostream &out, Coordinate &coor); 10 | public: 11 | Coordinate(int x = 0, int y = 0); 12 | void printCoordinate(); 13 | bool operator==(Coordinate &coor); 14 | 15 | private: 16 | int m_iX; 17 | int m_iY; 18 | }; -------------------------------------------------------------------------------- /imooc_code/data_structure/List/List.h: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Superone77/Cpp-basic-learning/82f8f452d06ba09d4636e19769c9d072b576ece3/imooc_code/data_structure/List/List.h -------------------------------------------------------------------------------- /imooc_code/data_structure/List/demo.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Superone77/Cpp-basic-learning/82f8f452d06ba09d4636e19769c9d072b576ece3/imooc_code/data_structure/List/demo.cpp -------------------------------------------------------------------------------- /imooc_code/data_structure/List/通讯录/List.h: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Superone77/Cpp-basic-learning/82f8f452d06ba09d4636e19769c9d072b576ece3/imooc_code/data_structure/List/通讯录/List.h -------------------------------------------------------------------------------- /imooc_code/data_structure/List/通讯录/Node.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include"Person.h" 4 | 5 | class Node 6 | { 7 | public: 8 | Person data; 9 | Node *next; 10 | void printNode(); 11 | }; -------------------------------------------------------------------------------- /imooc_code/data_structure/List/通讯录/Person.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | 8 | class Person 9 | { 10 | friend ostream &operator<<(ostream &out, Person &person); 11 | public: 12 | string name; 13 | string phone; 14 | Person &operator=(Person &person); 15 | bool operator==(Person &person); 16 | 17 | }; 18 | 19 | -------------------------------------------------------------------------------- /imooc_code/data_structure/List/通讯录/demo.cpp: -------------------------------------------------------------------------------- 1 | #include"List.h" 2 | #include"Node.h" 3 | #include 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | 9 | 10 | int main() 11 | { 12 | Node node1; 13 | node1.data.name = "test1"; 14 | node1.data.phone = "123456"; 15 | Node node2; 16 | node2.data.name = "test2"; 17 | node2.data.phone = "234567"; 18 | 19 | List *pList = new List(); 20 | pList->ListInsertTail(&node1); 21 | pList->ListInsertTail(&node2); 22 | 23 | pList->ListTraverse(); 24 | 25 | delete pList; 26 | pList = NULL; 27 | 28 | system("pause"); 29 | return 0; 30 | 31 | 32 | } -------------------------------------------------------------------------------- /imooc_code/data_structure/List/通讯录/node.cpp: -------------------------------------------------------------------------------- 1 | #include"node.h" 2 | #include 3 | 4 | using namespace std; 5 | 6 | void 7 | Node::printNode() 8 | { 9 | cout << data << endl; 10 | } -------------------------------------------------------------------------------- /imooc_code/data_structure/List/通讯录/person.cpp: -------------------------------------------------------------------------------- 1 | #include"Person.h" 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | Person &Person::operator=(Person &person) 8 | { 9 | this->name = person.name; 10 | this->phone = person.phone; 11 | return *this; 12 | } 13 | 14 | bool Person::operator==(Person &person) 15 | { 16 | if (this->name == person.name&&this->phone == person.phone) 17 | { 18 | return true; 19 | } 20 | 21 | return false; 22 | } 23 | ostream &operator<<(ostream &out, Person &person) 24 | { 25 | out << person.name << "---------" << person.phone << endl; 26 | return out; 27 | } -------------------------------------------------------------------------------- /imooc_code/data_structure/Map/CMap.h: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Superone77/Cpp-basic-learning/82f8f452d06ba09d4636e19769c9d072b576ece3/imooc_code/data_structure/Map/CMap.h -------------------------------------------------------------------------------- /imooc_code/data_structure/Map/Edge.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | class Edge 4 | { 5 | public: 6 | Edge(int nodeIndexA = 0, int nodeIndexB = 0, int weightValue = 0); 7 | int m_iNodeIndexA; 8 | int m_iNodeIndexB; 9 | int m_iWeightValue; 10 | bool m_bSelected; 11 | }; -------------------------------------------------------------------------------- /imooc_code/data_structure/Map/Node.cpp: -------------------------------------------------------------------------------- 1 | #include"Node.h" 2 | 3 | Node::Node(char data) 4 | { 5 | m_cData = data; 6 | m_bIsVisited = false; 7 | } -------------------------------------------------------------------------------- /imooc_code/data_structure/Map/Node.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | class Node 4 | { 5 | public: 6 | Node(char data = 0); 7 | char m_cData; 8 | bool m_bIsVisited; 9 | }; -------------------------------------------------------------------------------- /imooc_code/data_structure/Map/demo.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Superone77/Cpp-basic-learning/82f8f452d06ba09d4636e19769c9d072b576ece3/imooc_code/data_structure/Map/demo.cpp -------------------------------------------------------------------------------- /imooc_code/data_structure/Map/edge.cpp: -------------------------------------------------------------------------------- 1 | #include"Edge.h" 2 | 3 | using namespace std; 4 | 5 | Edge::Edge(int nodeIndexA, int nodeIndexB, int weightValue) 6 | { 7 | m_iNodeIndexA = nodeIndexA; 8 | m_iNodeIndexB = nodeIndexB; 9 | m_iWeightValue = weightValue; 10 | m_bSelected = false; 11 | } -------------------------------------------------------------------------------- /imooc_code/data_structure/Queue/Myqueue.h: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Superone77/Cpp-basic-learning/82f8f452d06ba09d4636e19769c9d072b576ece3/imooc_code/data_structure/Queue/Myqueue.h -------------------------------------------------------------------------------- /imooc_code/data_structure/Queue/customer.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Superone77/Cpp-basic-learning/82f8f452d06ba09d4636e19769c9d072b576ece3/imooc_code/data_structure/Queue/customer.cpp -------------------------------------------------------------------------------- /imooc_code/data_structure/Queue/customer.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | using namespace std; 4 | 5 | class Customer 6 | { 7 | public: 8 | Customer(string name ="", int age=0); 9 | void printinfo() const; 10 | 11 | private: 12 | string m_name; 13 | int m_age; 14 | }; -------------------------------------------------------------------------------- /imooc_code/data_structure/Queue/demo.cpp: -------------------------------------------------------------------------------- 1 | #include"Myqueue.h" 2 | #include 3 | #include 4 | #include"customer.h" 5 | 6 | using namespace std; 7 | 8 | int main() 9 | { 10 | MyQueue *p = new MyQueue(4); 11 | Customer c1("zhang", 20); 12 | Customer c2("Li", 30); 13 | Customer c3("wang", 20); 14 | 15 | p->EnQueue(c1); 16 | p->EnQueue(c2); 17 | p->EnQueue(c3); 18 | 19 | p->QueueTraverse(); 20 | 21 | Customer c4("", 0); 22 | p->DeQueue(c4); 23 | c4.printinfo(); 24 | 25 | p->QueueTraverse(); 26 | 27 | system("pause"); 28 | return 0; 29 | } -------------------------------------------------------------------------------- /imooc_code/data_structure/Queue/myqueue.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include"Myqueue.h" 3 | using namespace std; 4 | 5 | MyQueue::MyQueue(int queueCapacity) 6 | { 7 | m_pQueue = new Customer[queueCapacity]; 8 | m_iQueueCapacity = queueCapacity; 9 | ClearQueue(); 10 | } 11 | 12 | MyQueue::~MyQueue() 13 | { 14 | delete[] m_pQueue; 15 | m_pQueue = NULL; 16 | } 17 | 18 | void 19 | MyQueue::ClearQueue() 20 | { 21 | m_iQueueLen = 0; 22 | m_iHead = 0; 23 | m_iTail = 0; 24 | } 25 | 26 | bool 27 | MyQueue::QueueEmpty() const 28 | { 29 | if (m_iQueueLen == 0) 30 | return true; 31 | else 32 | return false; 33 | } 34 | 35 | bool 36 | MyQueue::QueueFull() const 37 | { 38 | if (m_iQueueLen == m_iQueueCapacity) 39 | return true; 40 | else 41 | return false; 42 | } 43 | 44 | int 45 | MyQueue::QueueLength() const 46 | { 47 | return m_iQueueLen; 48 | } 49 | 50 | bool 51 | MyQueue::EnQueue(Customer element) 52 | { 53 | if (m_iQueueLen == m_iQueueCapacity) 54 | return false; 55 | m_pQueue[m_iTail] = element; 56 | m_iTail++; 57 | m_iTail = m_iTail % m_iQueueCapacity; 58 | m_iQueueLen++; 59 | return true; 60 | } 61 | 62 | bool 63 | MyQueue::DeQueue(Customer &element) 64 | { 65 | if (m_iQueueLen == 0) 66 | return false; 67 | element = m_pQueue[m_iHead]; 68 | m_iHead++; 69 | m_iHead = m_iHead % m_iQueueCapacity; 70 | m_iQueueLen--; 71 | return true; 72 | } 73 | 74 | void 75 | MyQueue::QueueTraverse() 76 | { 77 | for (int i = m_iHead; i < m_iQueueLen + m_iHead;i++) 78 | { 79 | m_pQueue[i].printinfo(); 80 | 81 | } 82 | } 83 | 84 | -------------------------------------------------------------------------------- /imooc_code/data_structure/Queue/数组存储的线性表.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Superone77/Cpp-basic-learning/82f8f452d06ba09d4636e19769c9d072b576ece3/imooc_code/data_structure/Queue/数组存储的线性表.cpp -------------------------------------------------------------------------------- /imooc_code/data_structure/Stack/MyStack.h: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Superone77/Cpp-basic-learning/82f8f452d06ba09d4636e19769c9d072b576ece3/imooc_code/data_structure/Stack/MyStack.h -------------------------------------------------------------------------------- /imooc_code/data_structure/Stack/demo.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Superone77/Cpp-basic-learning/82f8f452d06ba09d4636e19769c9d072b576ece3/imooc_code/data_structure/Stack/demo.cpp -------------------------------------------------------------------------------- /imooc_code/data_structure/Stack/demo2.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Superone77/Cpp-basic-learning/82f8f452d06ba09d4636e19769c9d072b576ece3/imooc_code/data_structure/Stack/demo2.cpp -------------------------------------------------------------------------------- /imooc_code/data_structure/Stack/demo3.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Superone77/Cpp-basic-learning/82f8f452d06ba09d4636e19769c9d072b576ece3/imooc_code/data_structure/Stack/demo3.cpp -------------------------------------------------------------------------------- /imooc_code/data_structure/Stack/demo4.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Superone77/Cpp-basic-learning/82f8f452d06ba09d4636e19769c9d072b576ece3/imooc_code/data_structure/Stack/demo4.cpp -------------------------------------------------------------------------------- /imooc_code/data_structure/Tree(List)/Node.h: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Superone77/Cpp-basic-learning/82f8f452d06ba09d4636e19769c9d072b576ece3/imooc_code/data_structure/Tree(List)/Node.h -------------------------------------------------------------------------------- /imooc_code/data_structure/Tree(List)/Tree.cpp: -------------------------------------------------------------------------------- 1 | #include"Tree.h" 2 | #include 3 | 4 | using namespace std; 5 | 6 | Tree::Tree() 7 | { 8 | m_pRoot = new Node(); 9 | } 10 | 11 | Tree::~Tree() 12 | { 13 | DeleteNode(0, NULL); 14 | //m_pRoot->DeleteNode(); 15 | } 16 | 17 | Node* 18 | Tree::SearchNode(int nodeIndex) 19 | { 20 | return m_pRoot->SearchNode(nodeIndex); 21 | } 22 | 23 | 24 | bool 25 | Tree::AddNode(int nodeIndex, int direction, Node *pNode) 26 | { 27 | Node *temp = SearchNode(nodeIndex); 28 | if (temp == NULL) 29 | { 30 | return false; 31 | } 32 | 33 | Node *node = new Node(); 34 | node->index = pNode->index; 35 | node->data = pNode->data; 36 | node->pParent = temp; 37 | 38 | if (direction == 0) 39 | { 40 | temp->pLChild = node; 41 | } 42 | if (direction == 1) 43 | { 44 | temp->pRChild = node; 45 | } 46 | 47 | return true; 48 | 49 | } 50 | 51 | bool 52 | Tree::DeleteNode(int nodeIndex, Node *pNode) 53 | { 54 | Node *temp = SearchNode(nodeIndex); 55 | if (temp == NULL) 56 | { 57 | return false; 58 | } 59 | 60 | if (pNode != NULL) 61 | { 62 | pNode->data = temp->data; 63 | } 64 | 65 | temp->DeleteNode(); 66 | 67 | return true; 68 | 69 | } 70 | 71 | void 72 | Tree::PreorderTraversal() 73 | { 74 | m_pRoot->PreorderTraversal(); 75 | } 76 | 77 | void 78 | Tree::InorderTraversal() 79 | { 80 | m_pRoot->InorderTraversal(); 81 | } 82 | 83 | void 84 | Tree::PostorderTraversal() 85 | { 86 | m_pRoot->PostorderTraversal(); 87 | } -------------------------------------------------------------------------------- /imooc_code/data_structure/Tree(List)/Tree.h: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Superone77/Cpp-basic-learning/82f8f452d06ba09d4636e19769c9d072b576ece3/imooc_code/data_structure/Tree(List)/Tree.h -------------------------------------------------------------------------------- /imooc_code/data_structure/Tree(List)/demo.cpp: -------------------------------------------------------------------------------- 1 | #include"Node.h" 2 | #include"Tree.h" 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | int main() 9 | { 10 | 11 | Node *node1 = new Node(); 12 | node1->index = 1; 13 | node1->data = 5; 14 | 15 | Node *node2 = new Node(); 16 | node2->index = 2; 17 | node2->data = 8; 18 | 19 | Node *node3 = new Node(); 20 | node3->index = 3; 21 | node3->data = 2; 22 | 23 | Node *node4 = new Node(); 24 | node4->index = 4; 25 | node4->data = 6; 26 | 27 | Node *node5 = new Node(); 28 | node5->index = 5; 29 | node5->data = 9; 30 | 31 | Node *node6 = new Node(); 32 | node6->index = 6; 33 | node6->data = 7; 34 | 35 | 36 | Tree *tree = new Tree(); 37 | tree->AddNode(0, 0, node1); 38 | tree->AddNode(0, 1, node2); 39 | 40 | tree->AddNode(1, 0, node3); 41 | tree->AddNode(1, 1, node4); 42 | 43 | tree->AddNode(2, 0, node5); 44 | tree->AddNode(2, 1, node6); 45 | 46 | tree->DeleteNode(6, NULL); 47 | //tree->PreorderTraversal(); 48 | //tree->InorderTraversal(); 49 | tree->PostorderTraversal(); 50 | 51 | 52 | delete tree; 53 | 54 | system("pause"); 55 | return 0; 56 | } -------------------------------------------------------------------------------- /imooc_code/data_structure/Tree/Tree.h: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Superone77/Cpp-basic-learning/82f8f452d06ba09d4636e19769c9d072b576ece3/imooc_code/data_structure/Tree/Tree.h -------------------------------------------------------------------------------- /imooc_code/data_structure/Tree/demo.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #include"Tree.h" 5 | 6 | using namespace std; 7 | 8 | int main() 9 | { 10 | int root = 3; 11 | Tree *pTree = new Tree(10, &root); 12 | 13 | int node1 = 5; 14 | int node2 = 8; 15 | pTree->AddNode(0, 0, &node1); 16 | pTree->AddNode(0, 1, &node2); 17 | 18 | int node3 = 2; 19 | int node4 = 6; 20 | 21 | pTree->AddNode(1, 0, &node3); 22 | pTree->AddNode(1, 1, &node4); 23 | 24 | int node5 = 9; 25 | int node6 = 7; 26 | 27 | pTree->AddNode(2, 0, &node5); 28 | pTree->AddNode(2, 1, &node6); 29 | 30 | int node = 0; 31 | pTree->DeleteNode(6, &node); 32 | cout << endl << node << endl; 33 | 34 | pTree->TreeTraverse(); 35 | 36 | int *p=pTree->SearchNode(2); 37 | 38 | cout << endl<<*p << endl; 39 | 40 | delete pTree; 41 | pTree = NULL; 42 | 43 | system("pause"); 44 | return 0; 45 | } 46 | 47 | -------------------------------------------------------------------------------- /imooc_code/data_structure/Tree/tree.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Superone77/Cpp-basic-learning/82f8f452d06ba09d4636e19769c9d072b576ece3/imooc_code/data_structure/Tree/tree.cpp -------------------------------------------------------------------------------- /imooc_code/data_structure/chain_list/List.h: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Superone77/Cpp-basic-learning/82f8f452d06ba09d4636e19769c9d072b576ece3/imooc_code/data_structure/chain_list/List.h -------------------------------------------------------------------------------- /imooc_code/data_structure/chain_list/demo.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Superone77/Cpp-basic-learning/82f8f452d06ba09d4636e19769c9d072b576ece3/imooc_code/data_structure/chain_list/demo.cpp -------------------------------------------------------------------------------- /imooc_code/data_structure/chain_list/node.cpp: -------------------------------------------------------------------------------- 1 | #include"node.h" 2 | #include 3 | 4 | using namespace std; 5 | 6 | void 7 | Node::printNode() 8 | { 9 | cout << data << endl; 10 | } -------------------------------------------------------------------------------- /imooc_code/data_structure/chain_list/node.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | class Node 4 | { 5 | public: 6 | int data; 7 | Node *next; 8 | void printNode(); 9 | }; -------------------------------------------------------------------------------- /imooc_code/mazecode/MyMazeMap.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | 4 | using namespace std; 5 | 6 | class MyMazeMap 7 | { 8 | public: 9 | MyMazeMap(); 10 | MyMazeMap(const MyMazeMap& C); 11 | void setMazeMap(int *mazeArr, int x, int y); 12 | void setMazeWall(const char wallSign); 13 | void setMazeWay(const char waySign); 14 | void showFactor(); 15 | void drawMap(); 16 | bool checkWall(int x, int y); 17 | int getmazeX(); 18 | int getmazeY(); 19 | char m_wallSign; 20 | char m_waySign; 21 | private: 22 | int m_mazeArr[10][10]; 23 | int m_mazeX; 24 | int m_mazeY; 25 | 26 | 27 | 28 | }; 29 | -------------------------------------------------------------------------------- /imooc_code/mazecode/MyMazer.h: -------------------------------------------------------------------------------- 1 | #pragma once\ 2 | #include 3 | #include"MyMazeMap.h" 4 | 5 | using namespace std; 6 | 7 | class MyMazer 8 | { 9 | public: 10 | MyMazer(); 11 | MyMazeMap map; 12 | void setPersonPosition(int x, int y); 13 | void setPersonSpeed(int speed); 14 | void setPersonChar(char personchar); 15 | void start(); 16 | private: 17 | int LastPersonX; 18 | int LastPersonY; 19 | int PersonX; 20 | int PersonY; 21 | int SleepTime; 22 | char PersonChar; 23 | int direction; 24 | private: 25 | void gotoxy(int x, int y); 26 | void direction_up(); 27 | void direction_down(); 28 | void direction_left(); 29 | void direction_right(); 30 | int turnDirection(); 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | }; 39 | -------------------------------------------------------------------------------- /imooc_code/mazecode/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include "MyMazeMap.h" 4 | #include "MyMazer.h" 5 | 6 | using namespace std; 7 | 8 | const int WALL = 1; 9 | const int ROAD = 0; 10 | const int SLOW = 3; 11 | const int MEDIUM = 2; 12 | const int FAST = 1; 13 | 14 | const int SUCCESS = 0; 15 | int main() 16 | { 17 | int map[8][9] = { 18 | {WALL,WALL,WALL,WALL,WALL,WALL,WALL,ROAD,WALL}, 19 | {WALL,WALL,WALL,WALL,ROAD,WALL,WALL,ROAD,WALL}, 20 | {WALL,WALL,WALL,WALL,ROAD,WALL,WALL,ROAD,WALL}, 21 | {WALL,WALL,WALL,WALL,ROAD,WALL,WALL,ROAD,WALL}, 22 | {WALL,WALL,ROAD,ROAD,ROAD,ROAD,WALL,ROAD,WALL}, 23 | {WALL,WALL,ROAD,WALL,WALL,ROAD,ROAD,ROAD,WALL}, 24 | {WALL,ROAD,ROAD,WALL,WALL,WALL,WALL,WALL,WALL}, 25 | {WALL,ROAD,WALL,WALL,WALL,WALL,WALL,WALL,WALL} 26 | }; 27 | MyMazeMap maze; 28 | 29 | maze.setMazeMap(&map[0][0], 8, 9); 30 | maze.setMazeWall('*'); 31 | //maze.showFactor(); 32 | maze.drawMap(); 33 | MyMazer mazer; 34 | mazer.map = maze; 35 | mazer.setPersonPosition(7, 1); 36 | mazer.setPersonSpeed(FAST); 37 | mazer.setPersonChar('T'); 38 | mazer.start(); 39 | 40 | cout << endl; 41 | system("pause"); 42 | return SUCCESS; 43 | } -------------------------------------------------------------------------------- /imooc_code/mazecode/readme.txt: -------------------------------------------------------------------------------- 1 | 慕课网C++课程封装篇作业,自动走迷宫; 2 | https://www.imooc.com/learn/405 3 | 4 | 遇到的问题与解决方案: 5 | 1.在构建地图的MyMazeMap类和小人移动的MyMazer类的交互上出现问题。 6 | 解决方案:在MyMazer类中在堆中建立MyMazeMap类对象map,使用拷贝构造函数将主程序中的建立的maze对象拷贝进入MyMazer类对象map中,使得构建地图的成员和成员函数可以被利用到MyMazer的方法中。 7 | 即通过map.() 8 | 9 | 2.光标的移动方式与迷宫建立的坐标系的差异 10 | 使用头文件windows.h中的光标相关操作。 11 | 12 | ``` 13 | void 14 | MyMazer::gotoxy(int x, int y) 15 | { 16 | HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE); 17 | COORD pos; 18 | pos.X = y; 19 | pos.Y = x; 20 | SetConsoleCursorPosition(hOut, pos); 21 | } 22 | ``` 23 | 光标的移动方式是以,屏幕水平方向为x轴,竖直方向为y轴。 24 | 25 | 迷宫的建立方式则是以,屏幕水平方向为y轴,竖直方向为x轴。 26 | 27 | ``` 28 | int map[8][9] = { 29 | {WALL,WALL,WALL,WALL,WALL,WALL,WALL,ROAD,WALL}, 30 | {WALL,WALL,WALL,WALL,ROAD,WALL,WALL,ROAD,WALL}, 31 | {WALL,WALL,WALL,WALL,ROAD,WALL,WALL,ROAD,WALL}, 32 | {WALL,WALL,WALL,WALL,ROAD,WALL,WALL,ROAD,WALL}, 33 | {WALL,WALL,ROAD,ROAD,ROAD,ROAD,WALL,ROAD,WALL}, 34 | {WALL,WALL,ROAD,WALL,WALL,ROAD,ROAD,ROAD,WALL}, 35 | {WALL,ROAD,ROAD,WALL,WALL,WALL,WALL,WALL,WALL}, 36 | {WALL,ROAD,WALL,WALL,WALL,WALL,WALL,WALL,WALL} 37 | }; 38 | ``` 39 | 40 | 所以在以上光标移动函数gotoxy中将,x,y对调输入。 41 | 42 | 3.行动方式选择 43 | 解决方法:转向函数+上下左右前进函数 44 | 上下左右前进函数负责在抹去原来位置的人,并且在他旁边指定方向的一格处输出新的人。 45 | 转向函数则是通过走迷宫的左手法则,即无论在什么方向上都可以进行判断: 46 | 是否已在迷宫最外层——是,SUCCESS 47 | | 48 | | 49 | 不是,左边是否有墙——没有,左转。 50 | | 51 | | 52 | 有,前方是否有墙——没有,前进 53 | | 54 | | 55 | 有,右方是否有墙——没有,右转 56 | | 57 | | 58 | 有,后退; 59 | 60 | 通过switch对转向函数的输出做判断,调用前进函数。 61 | 62 | 4.如何控制速度; 63 | Sleep语句 64 | Sleep(n)(windows.h) 65 | 程序暂停n毫秒。 66 | 67 | 5.如何在程序运行中退出程序 68 | exit(0),正常运行后退出程序。 69 | 70 | 71 | C++新手,还会继续努力。 --------------------------------------------------------------------------------