C++ Primer (第五版)-第一章 -初识C++开始


**

题记:写这个专栏目的是刷一遍c++知识点,并整理和记录c++ Primer的要点,提高个人的知识体系。同时向大师致敬。声明本专栏只用于学习交流之用。

**

一、源码下载

链接: 源码下载

在这里插入图片描述

二、第一章–开始

1.1编写一个简单的程序–初探c++

  int  main()
  {
   return 0;
 }

1、返回类型(return type)
2、函数名 (Function name)
3、形参列表(parameter list允许为空)
4、函数体 (function body )—花括号和语句块
在这里插入图片描述
在这里插入图片描述

编译:

在这里插入图片描述

1.2、初识输入输出

c++语言提供标准库(standard library),大部分使用iostream io库。包含istream 和ostream
在这里插入图片描述

//头文件,通常情况下,#include指令必须出现在所有函数之外。
//我们一般将一个程序的所有机nclude指令部放在源文件的开始位置
#include <iostream>

int main()
{
	// prompt user to enter two numbers
	/*
第一个输出运算符给用户打印一条消息。这个消息是一个字符串字面值常量Cstrmg
literal),是用一对双引号包围的字符序列。在双引号之间的文本被打印到标准输出。
第二个运算符打印endl,这是- 个被称为操纵符(manipul ator )的特殊值。写入end l
的效果是结束当前行, 并将与设备关联的缓冲区(buffer)中的内容刷到设备中。缓冲刷
新操作可以保证到目前为止程序所产生的所有输出有ni真正写入输出流中, 而不是仅停留在
内存中等待写入流。
*/
	std::cout << "Enter two numbers:" << std::endl; 
	int v1 = 0, v2 = 0;
	std::cin >> v1 >> v2;   
/*
向流写入数据
main的函数体的第一条语句执行了一个表达式( expression)。在C++中, 一个表达
式产生一个计算结果, 它由一个或多个运算对象和(通常是〉一个运算符组成。这条语句
中的表达式使用了输出运算符(《)在标准输出上打印消息:
*/
	std::cout << "The sum of " << v1 << " and " << v2
	          << " is " << v1 + v2 << std::endl;
	return 0;
}

输出结果:
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

1.3、注释

在这里插入图片描述
在这里插入图片描述

1.4、逻辑语句

#include

                                         while循环
int main()
{
    int sum = 0, val = 1;
    // keep executing the while as long as val is less than or equal to 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;
}

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

#include <iostream> 

int main() 
{
	int sum = 0, value = 0;

	// read until 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;
}

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

                              for循环
#include <iostream>
int main()
{
	int sum = 0;
	for (int i = -100; i <= 100; ++i)
    	sum += i;
	std::cout << sum << std::endl;
	return 0;
}

在这里插入图片描述

                                     if语句
#include <iostream>

int main()
{
	// currVal is the number we're counting; we'll read new values into val
	int currVal = 0, val = 0;

	// read first number and ensure that we have data to process
	if (std::cin >> currVal) {        
		int cnt = 1;  // store the count for the current value we're processing
		while (std::cin >> val) { // read the remaining numbers 
			if (val == currVal)   // if the values are the same
				++cnt;            // add 1 to cnt 
			else { // otherwise, print the count for the previous value
				std::cout << currVal << " occurs " 
				          << cnt << " times" << std::endl;
				currVal = val;    // remember the new value
				cnt = 1;          // reset the counter
			}
		}  // while loop ends here
		// remember to print the count for the last value in the file
		std::cout << currVal << " occurs " 
		          << cnt << " times" << std::endl;
	} // outermost if statement ends here
	return 0;
}

在这里插入图片描述
在这里插入图片描述

1.5、类简介

在这里插入图片描述

//sales_item.h
#ifndef SALESITEM_H
// we're here only if SALESITEM_H has not yet been defined 
#define SALESITEM_H

#include "Version_test.h" 

// Definition of Sales_item class and related functions goes here
#include <iostream>
#include <string>

class Sales_item {
// these declarations are explained section 7.2.1, p. 270 
// and in chapter 14, pages 557, 558, 561
friend std::istream& operator>>(std::istream&, Sales_item&);
friend std::ostream& operator<<(std::ostream&, const Sales_item&);
friend bool operator<(const Sales_item&, const Sales_item&);
friend bool 
operator==(const Sales_item&, const Sales_item&);
public:
    // constructors are explained in section 7.1.4, pages 262 - 265
    // default constructor needed to initialize members of built-in type
#if defined(IN_CLASS_INITS) && defined(DEFAULT_FCNS)
    Sales_item() = default;
#else
    Sales_item(): units_sold(0), revenue(0.0) { }
#endif
    Sales_item(const std::string &book):
              bookNo(book), units_sold(0), revenue(0.0) { }
    Sales_item(std::istream &is) { is >> *this; }
public:
    // operations on Sales_item objects
    // member binary operator: left-hand operand bound to implicit this pointer
    Sales_item& operator+=(const Sales_item&);
    
    // operations on Sales_item objects
    std::string isbn() const { return bookNo; }
    double avg_price() const;
// private members as before
private:
    std::string bookNo;      // implicitly initialized to the empty string
#ifdef IN_CLASS_INITS
    unsigned units_sold = 0; // explicitly initialized
    double revenue = 0.0;
#else
    unsigned units_sold;  
    double revenue;       
#endif
};

// used in chapter 10
inline
bool compareIsbn(const Sales_item &lhs, const Sales_item &rhs) 
{ return lhs.isbn() == rhs.isbn(); }

// nonmember binary operator: must declare a parameter for each operand
Sales_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.isbn() == rhs.isbn();
}

inline bool 
operator!=(const Sales_item &lhs, const Sales_item &rhs)
{
    return !(lhs == rhs); // != defined in terms of operator==
}

// assumes that both objects refer to the same ISBN
Sales_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 ISBN
Sales_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
}

std::istream& 
operator>>(std::istream& in, Sales_item& s)
{
    double price;
    in >> s.bookNo >> 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;
}

std::ostream& 
operator<<(std::ostream& out, const Sales_item& s)
{
    out << s.isbn() << " " << s.units_sold << " "
        << s.revenue << " " << s.avg_price();
    return out;
}

double Sales_item::avg_price() const
{
    if (units_sold) 
        return revenue/units_sold; 
    else 
        return 0;
}
#endif
//Sales_item.cpp
#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;
}

在这里插入图片描述

  sales_item对象相加
#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;
}

在这里插入图片描述

在这里插入图片描述

                        初识成员函数
#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.isbn() == item2.isbn()) {
    	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
	}
}

在这里插入图片描述
在这里插入图片描述

#include <iostream>
#include "Sales_item.h"

int main() 
{
    Sales_item total; // variable to hold data for the next transaction

    // read the first transaction and ensure that there are data to process
    if (std::cin >> total) {
		Sales_item trans; // variable to hold the running sum
        // read and process the remaining transactions
        while (std::cin >> trans) {
			// if we're still processing the same book
            if (total.isbn() == trans.isbn()) 
                total += trans; // update the running total 
            else {              
		        // print results for the previous book 
                std::cout << total << std::endl;  
                total = trans;  // total now refers to the next book
            }
		}
        std::cout << total << std::endl; // print the last transaction
    } else {
        // no input! warn the user
        std::cerr << "No data?!" << std::endl;
        return -1;  // indicate failure
    }

    return 0;
}

1.6、小结

在这里插入图片描述

1.7、术语表

在这里插入图片描述在这里插入图片描述
在这里插入图片描述

  • 0
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 《C Primer第五版》是一本经典的C语言教材,旨在为读者提供学习和掌握C语言的基础知识,深入了解C语言的语法和特性,以及如何在C语言开发程序。整本书分为三个部分,分别介绍C语言基础知识、控制语句和函数,以及数组、指针和字符串等高级主题。其中,基础知识部分讲述了C语言基本的语法和数据类型,详细介绍了变量、表达式、运算符、流控制和函数的定义和调用。控制语句和函数部分深入讨论了C语言中的分支结构、循环结构和函数的定义和使用。高级主题部分介绍了C语言中的数组、指针、字符串和结构体等高级数据类型,并讲述了如何利用这些特性开发高效的程序。另外,本书还提供了大量的示例代码和练习题,帮助读者更好地理解和掌握C语言的编程技巧。此外,《C Primer第五版》的电子书版本具有兼容性强、文字清晰、便于查询等优点,是学习和使用C语言的优秀参考资料。总之,这本书对于想要学习C语言的人来说是一本非常好的入门教材,可以帮助读者在学习C语言过程中更加深入地理解和应用C语言。 ### 回答2: 《C Primer第五版》是一本介绍C语言基础概念的经典电子书。本书共分为18章,全面介绍了C语言的基本语法、控制流、数据类型、函数、指针、数组、字符串、结构体、文件I/O等内容。 本书内容详实,通俗易懂,适合C语言初学者阅读。每个章节都附有大量的示例代码、习题以及解答,加深了读者对C语言概念的理解和掌握。 此外,本书的编排合理,从基础到深入,逐步引入C语言的各个概念,让读者能够逐步掌握C语言编程的基本方法和技巧。作者还通过大量的实例来说明不同技术之间的联系和区别,为初学者提供了实用的学习经验。 总之,《C Primer第五版》是一本非常优秀的C语言入门选手,它不仅适合初学者,也适合具有一定编程经验的读者进行巩固和提高。此外,电子书形式更加便于读者学习和查阅,建议广大读者尝试阅读。 ### 回答3: 《C Primer第五版》是一本针对初学者而编写的C语言教材,由Lippman、Lajoie和Moo合著。本书全面讲解了C语言的基础知识和开发技巧,并以简洁明了的语言、清晰的示例代码和丰富的练习题为特点。这本书可以帮助读者快速成为一个合格的C语言程序员。 本书分为三部分,分别介绍了C语言的基本结构、C语言程序设计和高级C语言编程。第一部分主要讲解了C语言的语法规则、数据类型、变量、运算符等基础知识。第二部分主要讲解了程序设计中的控制结构、数组、函数、指针等内容,包括如何进行模块化设计、如何组织代码、如何调试程序等。第三部分主要讲解了一些高级编程技术,如结构体、链表、文件处理等内容,此外还介绍了C++和C语言库函数的使用。 《C Primer第五版》的优点不仅在于其全面性和丰富性,更在于它注重实践教学。本书在讲解知识点的同时提供了大量的示例程序,并在每章末都有大量练习题供读者练习。这样的设计可以帮助读者更深刻地理解和运用各种知识点,并且能够更快速地掌握C语言的编程技巧和实践经验。 总之,如果你想学习C语言或者提高自己的C语言编程能力,那么《C Primer第五版》绝对是一本不可多得的教材,它可以帮助你轻松地掌握这门语言并成为一个合格的C语言程序员。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值