熟悉编译器

g++

  • 编译:g++ --std=c++11 ch01.cpp -o main
  • 运行:./prog1
  • 查看运行状态:echo $?
  • 编译多个文件:g++ ch2.cpp Sales_item.cc -o main

输入 g++ --help,查看编译器选项,部分常见选项如下:

1
2
3
4
5
6
-E                       Preprocess only; do not compile, assemble or link
-S Compile only; do not assemble or link
-c Compile and assemble, but do not link
-o <file> Place the output into <file>
-pie Create a position independent executable
-shared Create a shared library

获得程序状态:

  • windows: echo %ERRORLEVEL%
  • UNIX: echo $?

IO

  • #include <iostream>
  • std::cout << "hello"
  • std::cin >> v1

记住>><<返回的结果都是左操作数,也就是输入流和输出流本身。

endl:这是一个被称为操纵符(manipulator)的特殊值,效果是结束当前行,并将设备关联的缓冲区(buffer)中的内容刷到设备中

UNIX和Mac下键盘输入文件结束符:ctrl+d,Windows下:ctrl+z

头文件:类的类型一般存储在头文件中,标准库的头文件使用<>,非标准库的头文件使用""。申明写在.h文件,定义实现.cpp文件。

避免多次包含同一头文件

1
2
3
4
#ifndef SALESITEM_H
#define SALESITEM_H
// Definition of Sales_itemclass and related functions goes here
#endif

成员函数(类方法):使用.调用。

命名空间(namespace):使用作用域运算符::调用。

注释

  • 单行注释: //
  • 多行注释: /**/。编译器将/**/之间的内容都作为注释内容忽略。注意不能嵌套

使用文件重定向

./main <infile >outfile