目录
每个C++程序都包含一个或者多个函数(function),其中一个必须命名为mian主函数。
编译器常见错误:语法错误/类型错误/声明错误,修正错误重新编译就是所谓“编辑--编译--调试”周期
Sales_item类表示一本书的总销售额,售出册数,平均售价。
1.1你知道如何编写一个简单的C++程序吗?
每个C++程序都包含一个或者多个函数(function),其中一个必须命名为mian主函数。
int main()
{
return 0;
}
一个函数定义包含四部分:返回类型,函数名,一个括号包围的形参列表(允许为空),函数体(左右花括号包含的语句块)。
编译,运行程序
编写好程序后就要编译它,,很多PC机子上的编译器都具备集成开发环境(Integrated Developed Environment,简称IDE),先将精力集中学好C++再学IDE。
从命令行运行编译器详情见C++ Primer3-4
初识输入输出
C++语言并未定义任何输入输出(I/O)语句,是由一个包含了全面标准库来提供I/O机制(或者其他)。iostream库包含两个基础类型,istream输入流,ostream输出流,一个流就是一个字符序列,术语"流"指随着时间推移字符顺序生成或消耗的。
用一个名为cin(标准输入)的istream类型的对象来处理输入
用一个名为cout(标准输出)的ostream类型的对象来处理输出,用cerr(标准错误)输出警告和错误信息,用clog来输出程序运行时的一般性信息。
向流写入数据
输出运算符<<,在标准输出上打印信息。
std::cout<<"Enter two numbers:"<<std::endl;
//等价于
(std::cout<<"Enter two numbers:")<<std::endl;
//等价于
std::cout<<"Enter two numbers:";
std::cout<<std::endl;
endl是一个被称为操纵符的特殊値,写入endl是为了结束当前行,并将与设备关联的缓冲区中的内容刷到设备中。缓冲刷新操作可以保证到目前为止程序所产生的所有输出都能真正写入输出流中而不是仅仅停留在内存中等待写入流。
注意打印语句应该保证一直"刷新流",否则如果程序崩溃输出可能还在缓冲区从而导致程序崩溃位置的错误判断。
使用标准库中的名字
前缀std::指出名字cout和endl是定义在名为std的命名空间namespace中的,命名空间可以帮助我们避免不经意间名字定义冲突和库中同名字的冲突,标准库定义 的所有名字都在std中。
这种方法副作用是当使用一个标准库名字时必须显示说明我们想用来自std中的名字,用作用域运算符::来指出我们想用定义在std命名空间的名字,比如std 中的cout,std : : cout
从流读取数据
输入运算符>>
int i = 0, j = 0;
//std::cin >> i >> j;
//等价于
//(std::cin >> i) >> j;
//等价于
std::cin >> i;
std::cin >> j;
//输出
std::cout << i << "and" << j << std::endl;
C++注释种类
1.单行注释以双斜线 / / 开始以换行符结束。
2.界定符注释(/*和*/),注意界定符不能嵌套
控制流
While语句(反复执行一段代码直到给定条件为假为止)
#include<iostream>
int main()
{
int sum = 0, val = 1;
while (val <= 10)
{
sum += val;
val++;
}
std::cout << "sum和为" << sum << std::endl;
//打印55
}
for语句可以简化繁琐的while语句;每个for语句都包含两部分:循环头和循环体。循环头控制循环体执行次数:由一个初始化语句,一个循环条件,一个表达式组成。
int main()
{
int sum = 0;
for (int val = 1; val <= 10; val++)
{
sum += val;
}
std::cout << "sum和为" << sum << std::endl;
//打印55
return 0;
}
读取数量不定的输入数据(vs打印不出来)
int main()
{
int sum = 0, val = 1;
while (std::cin>>val)
{
sum += val;
//val++;
}
std::cout << "sum和为" << sum << std::endl;
return 0;
}
编译器常见错误:语法错误/类型错误/声明错误,修正错误重新编译就是所谓“编辑--编译--调试”周期
C++用=赋值,==作为相等运算符
类简介
在C++中我们可以通过定义一个类来定义自己的数据结构。一个类定义一个类型以及与其关联的一组操作,类机制是C++最重要的特性之一,比如istream和ostream都是类,而类类型是类定义的类型。下面来简单介绍一下如何定义一个数据结构来表示销售总额:
Sales_item类
Sales_item类表示一本书的总销售额,售出册数,平均售价。
我们怎么实现类操作,比如Sales_item类定义一个名为Sales_item类型,与内置类型一样可以定义变量。
关于Sales_item.h 头文件使用的若干问题,比如打不开头文件
拷贝Sales_item源码过去
/*
* This file contains code from "C++ Primer, Fifth Edition", by Stanley B.
* Lippman, Josee Lajoie, and Barbara E. Moo, and is covered under the
* copyright and warranty notices given in that book:
*
* "Copyright (c) 2013 by Objectwrite, Inc., Josee 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 Permissions Department
* One Lake Street
* Upper Saddle River, NJ 07458
* Fax: (201) 236-3290
*/
/* This file defines the Sales_item class used in chapter 1.
* The code used in this file will be explained in
* Chapter 7 (Classes) and Chapter 14 (Overloaded Operators)
* Readers shouldn't try to understand the code in this file
* until they have read those chapters.
*/
#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
#pragma once
- 官网下载安装
如果发生这种问题
Version_test.h
/*
* This file contains code from "C++ Primer, Fifth Edition", by Stanley B.
* Lippman, Josee Lajoie, and Barbara E. Moo, and is covered under the
* copyright and warranty notices given in that book:
*
* "Copyright (c) 2013 by Objectwrite, Inc., Josee 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 Permissions Department
* One Lake Street
* Upper Saddle River, NJ 07458
* Fax: (201) 236-3290
*/
#ifndef VERSION_TEST_H
#define VERSION_TEST_H
/* As of the first printing of C++ Primer, 5th Edition (July 2012),
* the Microsoft Complier did not yet support a number of C++ 11 features.
*
* The code we distribute contains both normal C++ code and
* workarounds for missing features. We use a series of CPP variables to
* determine whether a given features is implemented in a given release
* of the MS compiler. The base version we used to test the code in the book
* is Compiler Version 17.00.50522.1 for x86.
*
* When new releases are available we will update this file which will
* #define the features implmented in that release.
*/
#if _MSC_FULL_VER == 170050522 || _MSC_FULL_VER == 170050727
// base version, future releases will #define those features as they are
// implemented by Microsoft
/* Code in this delivery use the following variables to control compilation
Variable tests C++ 11 Feature
CONSTEXPR_VARS constexpr variables
CONSTEXPR_FCNS constexpr functions
CONSTEXPR_CTORS constexpr constructors and other member functions
DEFAULT_FCNS = default
DELETED_FCNS = delete
FUNC_CPP __func__ local static
FUNCTION_PTRMEM function template with pointer to member function
IN_CLASS_INITS in class initializers
INITIALIZER_LIST library initializer_list<T> template
LIST_INIT list initialization of ordinary variables
LROUND lround function in cmath
NOEXCEPT noexcept specifier and noexcept operator
SIZEOF_MEMBER sizeof class_name::member_name
TEMPLATE_FCN_DEFAULT_ARGS default template arguments for function templates
TYPE_ALIAS_DECLS type alias declarations
UNION_CLASS_MEMS unions members that have constructors or copy control
VARIADICS variadic templates
*/
#endif // ends compiler version check
#ifndef LROUND
inline long lround(double d)
{
return (d >= 0) ? long(d + 0.5) : long(d - 0.5);
}
#endif
#endif // ends header guard#pragma once#pragma once
接下来就可以编写一个简易的Sales_item
#include<iostream>
#include"Sales_item.h"
#include"Version_test.h"
int main()
{
Sales_item book;
//读入ISBN号,售出册数以及销售价格
std::cin >> book;
//写入ISBN号,售出册数,总销售额以及平均价格
std::cout << book << std::endl;
//输入0-201-70353-x 4 24.99
//输出0-201-70353-x 4 99.96 24.99
return 0;
}
//包含来自标准库的头文件应该用尖括号(< >)包围头文件名,对于不属于标准库的头文件用双引号包围。
Sales_item对象的加法
#include<iostream>
#include"Sales_item.h"
#include"Version_test.h"
int main()
{
Sales_item item1,item2;
//读入ISBN号,售出册数以及销售价格
std::cin >> item1>>item2;
//写入ISBN号,售出册数,总销售额以及平均价格
std::cout << item1+item2 << std::endl;//两个对象相加
//输入0-201-78345-x 3 20.00
//输入0-201-78345-x 2 25.00
//输出0-201-78345-x 5 110 22
return 0;
}
文件重定向:详情见书p19
初识成员函数
#include<iostream>
#include"Sales_item.h"
#include"Version_test.h"
int main()
{
Sales_item item1, item2;
std::cin >> item1 >> item2;
if (item1.isbn() == item2.isbn())//检查两个对象isbn是否相同
{
std::cout << item1 + item2 << std::endl;//两个对象相加
}
else
{
std::cerr << "Data must refer to same ISBN" << std::endl;
//return -1或者return 0
}
//输入0-201-78345-x 3 20.00
//输入0-201-88945-x 2 25.00
//输出Data must refer to same ISBN
return 0;
}
什么是成员函数?
调用名为isbn的成员函数,成员函数是定义为类的一部分函数,有时也叫方法
以类对象名调用成员函数
item1.isbn()
点运算符(只能用于类类型的对象)表示“名为item1的对象的isbn成员”。
运算符右侧的对象必须是该类型的一个成员名
成员函数isbn并不接受参数,调用它只返回书名号ISBN
//书店程序
#include<iostream>
#include"Sales_item.h"
#include"Version_test.h"
int main()
{
Sales_item total;
//读入ISBN号,售出册数以及销售价格
if (std::cin >> total)
{
Sales_item trans;
while (std::cin >> trans)
{
if (total.isbn() == trans.isbn())
{
total += trans;
}
else
{
std::cout << total << std::endl;
total = trans;
}
}
std::cout << total << std::endl;
}
else
{
std::cerr << "No data?"<<std::endl;
return -1;//表示失败
}
return 0;
}