首页 > 代码库 > 第一章 快速入门

第一章 快速入门


C++ Primer 中文版,第4版

/*

第一章 快速入门
第二章 变量和基本类型
第三章 标准库类型
第四章 数组和指针
第五章 表达式
第六章 语句
第七章 函数
第八章 标准IO库
第九章 顺序容器
第十章 关联容器
第11章 泛型算法
第12章 类
第13章 复制控制
第14章 重载操作符与转换
第15章 面向对象编程
第16章 模板和泛型编程
第17章 用于大型程序的工具
第18章 特殊工具与技术

*/


/*

第一章 快速入门

第一部分:基本语言-------------------------------------------
第二章 变量和基本类型
第三章 标准库类型
第四章 数组和指针
第五章 表达式
第六章 语句
第七章 函数
第八章 标准IO库

第二部分:容器和算法----------------------------------------
第九章 顺序容器
第十章 关联容器
第11章 泛型算法

第三部分:类和数据抽象--------------------------------------
第12章 类
第13章 复制控制
第14章 重载操作符与转换

第四部分:面向对象编程与泛型编程--------------------------
第15章 面向对象编程
第16章 模板和泛型编程

第五部分:高级主题------------------------------------------
第17章 用于大型程序的工具
第18章 特殊工具与技术

*/

 

第一章  快速入门

// Sales_item.h

/* * This file contains code from "C++ Primer, Fourth Edition", by Stanley B. * Lippman, Jose Lajoie, and Barbara E. Moo, and is covered under the * copyright and warranty notices given in that book: *  * "Copyright (c) 2005 by Objectwrite, Inc., Jose Lajoie, and Barbara E. Moo." *  *  * "The authors and publisher have taken care in the preparation of this book, * but make no expressed or implied warranty of any kind and assume no * responsibility for errors or omissions. No liability is assumed for * incidental or consequential damages in connection with or arising out of the * use of the information or programs contained herein." *  * Permission is granted for this code to be used for educational purposes in * association with the book, given proper citation if and when posted or * reproduced.Any commercial use of this code requires the explicit written * permission of the publisher, Addison-Wesley Professional, a division of * Pearson Education, Inc. Send your request for permission, stating clearly * what code you would like to use, and in what specific way, to the following * address:  *  *     Pearson Education, Inc. *     Rights and Contracts Department *     75 Arlington Street, Suite 300 *     Boston, MA 02216 *     Fax: (617) 848-7047*/ #ifndef SALESITEM_H#define SALESITEM_H// Definition of Sales_item class and related functions goes here#include <iostream>#include <string>class Sales_item {friend bool operator==(const Sales_item&, const Sales_item&);// other members as beforepublic:    // added constructors to initialize from a string or an istream    Sales_item(const std::string &book):              isbn(book), units_sold(0), revenue(0.0) { }    Sales_item(std::istream &is) { is >> *this; }    friend std::istream& operator>>(std::istream&, Sales_item&);    friend std::ostream& operator<<(std::ostream&, const Sales_item&);public:    // operations on Sales_item objects    // member binary operator: left-hand operand bound to implicit this pointer    Sales_item& operator+=(const Sales_item&);    // other members as before    public:    // operations on Sales_item objects    double avg_price() const;    bool same_isbn(const Sales_item &rhs) const        { return isbn == rhs.isbn; }    // default constructor needed to initialize members of built-in type    Sales_item(): units_sold(0), revenue(0.0) { }// private members as beforeprivate:    std::string isbn;    unsigned units_sold;    double revenue;};// nonmember binary operator: must declare a parameter for each operandSales_item operator+(const Sales_item&, const Sales_item&);inline bool operator==(const Sales_item &lhs, const Sales_item &rhs){    // must be made a friend of Sales_item    return lhs.units_sold == rhs.units_sold &&           lhs.revenue == rhs.revenue &&       lhs.same_isbn(rhs);}inline bool operator!=(const Sales_item &lhs, const Sales_item &rhs){    return !(lhs == rhs); // != defined in terms of operator==}using std::istream; using std::ostream;// assumes that both objects refer to the same isbninlineSales_item& Sales_item::operator+=(const Sales_item& rhs) {    units_sold += rhs.units_sold;     revenue += rhs.revenue;     return *this;}// assumes that both objects refer to the same isbninlineSales_item operator+(const Sales_item& lhs, const Sales_item& rhs) {    Sales_item ret(lhs);  // copy lhs into a local object that we‘ll return    ret += rhs;           // add in the contents of rhs     return ret;           // return ret by value}inlineistream& operator>>(istream& in, Sales_item& s){    double price;    in >> s.isbn >> s.units_sold >> price;    // check that the inputs succeeded    if (in)        s.revenue = s.units_sold * price;    else         s = Sales_item();  // input failed: reset object to default state    return in;}inlineostream& operator<<(ostream& out, const Sales_item& s){    out << s.isbn << "\t" << s.units_sold << "\t"         << s.revenue << "\t" <<  s.avg_price();    return out;}inlinedouble Sales_item::avg_price() const{    if (units_sold)         return revenue/units_sold;     else         return 0;}#endif
View Code

 

Code:

// 1、编写简单的C++程序 ------------------------------------------------int main(){  return 0;}// 2、初窥输入/输出 ---------------------------------------------------#include <iostream>int main(){  std::cout << "Enter two numbers:" << std::endl;   int v1, v2;  std::cin >> v1 >> v2;     std::cout << "The sum of " << v1 << " and " << v2            << " is " << v1 + v2 << std::endl;  return 0;}// 3、关于注释 --------------------------------------------------------------/* Simple main function: Read two numbers and write their sum */#include <iostream>int main(){  // prompt user to enter two numbers  std::cout << "Enter two numbers:" << std::endl;   int v1, v2;           //uninitialized  std::cin >> v1 >> v2; // read input    return 0;}// 4、控制结构 -------------------------------------------------------------// while#include <iostream>int main(){  int sum = 0, val = 1;  // keep executing the while until val is greater than 10  while(val <= 10)  {    sum += val; // assigns sum + val to sum    ++val; // add 1 to val  }  std::cout << "Sum of 1 to 10 inclusive is " << sum << std::endl;  return 0;}// for#include <iostream>int main(){  int sum = 0;  // sum values from 1 up to 10 inclusive  for(int val = 1; val <= 10; ++val)    sum += val;  // equivalent to sum = sum + val  std::cout << "Sum of 1 to 10 inclusive is " << sum << std::endl;  return 0;}// if#include <iostream>int main(){  std::cout << "Enter two numbers:" << std::endl;  int v1, v2;  std::cin >> v1 >> v2; // read input  // use smaller number as lower bound for summation  // and larger number as upper bound  int lower, upper;  if(v1 <= v2)  {    lower = v1;    upper = v2;  }  else  {    lower = v2;    upper = v1;  }  int sum = 0;  // sum values from lower up to and including upper  for(int val = lower; val <= upper; ++val)    sum += val;  // sum = sum + val  std::cout << "Sum of " << lower << " to " << upper << " inclusive is " << sum    << std::endl;  return 0;}// end of file. Ctrl+z 可以模拟文件尾#include <iostream>int main(){  int sum = 0, value;  // read till end-of-file, calculating a running total of all values read  while(std::cin >> value)    sum += value;  // equivalent to sum = sum + value  std::cout << "Sum is: " << sum << std::endl;  return 0;}// 5、类的简介 ----------------------------------------------------/*必须将Sales_item.h文件,放在程序文件的同一目录下,这个程序才可以运行。Sales_item.h文件,目前不要求读者制作。Sales_item.h文件具体内容,在最前面。*/#include <iostream>#include "Sales_item.h"int main(){  Sales_item book;  // read ISBN, number of copies sold, and sales price  std::cin >> book;  // write ISBN, number of copies sold, total revenue, and average price  std::cout << book << std::endl;  return 0;}// input:   0-201-70353-X 4 24.99// 对象之和#include <iostream>#include "Sales_item.h"int main(){  Sales_item item1, item2;  std::cin >> item1 >> item2; // read a pair of transactions  std::cout << item1 + item2 << std::endl; // print their sum  return 0;}/*0-201-78345-X 3 20.000-201-78345-X 2 25.00*/// 成员函数#include <iostream>#include "Sales_item.h"int main(){  Sales_item item1, item2;  std::cin >> item1 >> item2;  // first check that item1 and item2 represent the same book  if(item1.same_isbn(item2))  {    std::cout << item1 + item2 << std::endl;    return 0; // indicate success  }  else  {    std::cerr << "Data must refer to same ISBN" << std::endl;    return  - 1; // indicate failure  }}/*0-201-78345-X 3 20.000-201-78345-X 2 25.000-201-78345-X 3 20.000-888-78345-X 2 25.00*/// 6、C++程序 ------------------------------------------------------#include <iostream>#include "Sales_item.h"int main(){  //  declare variables to hold running sum and data for the next record  Sales_item total, trans;  //  is there data to process?  if(std::cin >> total)  {    // if so, read the transaction records    while(std::cin >> trans)      if(total.same_isbn(trans))    //  match: update the running total        total = total + trans;      else    {      //  no match: print & assign to total      std::cout << total << std::endl;      total = trans;    }    //  remember to print last record    std::cout << total << std::endl;  }  else  {    //  no input!, warn the user    std::cout << "No data?!" << std::endl;    return  - 1; //  indicate failure  }  return 0;}

 

 

 

 

TOP

 

第一章 快速入门