ustc review for final exam chapters 1 20staff.ustc.edu.cn/~zlwang/oop/ppt/review_for_final.pdf ·...
TRANSCRIPT
USTC
Review for Final Exam
Chapters 1–20(“Programming and C++ in 75 minutes”)
王子磊 (Zilei Wang)
Email: [email protected]
http://vim.ustc.edu.cn
USTC AUTO
目标
教授/学习 基本的编程概念
关键的有用技术
基本的标准 C++ 设施
本课程学习后,你能够 编写小的通用 C++ 程序
阅读更大的程序
自学其他语言的基本知识
能够深入学习“高级C++程序设计”课程
本课程学习后,你仍不能成为 专家级程序员
C++ 语言专家
高级库的使用专家Stroustrup/PPP - April 2010
http://staff.ustc.edu.cn/~zlwang/
USTC AUTO
Chapter 1-2 Programming
为什么学习 C++?
为什么需要软件?
C++ 能用在哪里?
Hello World 程序
计算和链接
什么是程序设计?
集成开发环境 IDE
#include "std_lib_facilities.h " //header
int main() // where a C++ programs start
{
cout << "Hello, world\n";// output
keep_window_open(); // wait
return 0; // return success
}
http://staff.ustc.edu.cn/~zlwang/
USTC AUTO
Chapter 3 Types
内建类型:int, double,
bool, char
库类型:string, complex
输入输出
操作符及其重载
C++中的变量名
简单计算
字面常量
声明和初始化
类型安全
程序设计哲学
// inch to cm and cm to inch conversion:
int main()
{
const double cm_per_inch = 2.54;
int val;
char unit;
while (cin >> val >> unit) {// keep reading
if (unit == 'i') // 'i' for inch
cout << val << "in == “
<< val*cm_per_inch << "cm\n";
else if (unit == 'c') // 'c' for cm
cout << val << "cm == " << val/cm_per_inch << "in\n";
else
return 0; // terminate on a “bad // unit”, e.g. 'q'
}
}
http://staff.ustc.edu.cn/~zlwang/
USTC AUTO
Chapter 4 Computation
表达计算 正确性、简单性、高效性
分治
使用抽象
组织数据,vector
语言特性 表达式
• 布尔运算符 (e.g. ||)
• 缩略运算符 (e.g. +=)
语句
控制流
函数
算法
// Eliminate the duplicate words; copying unique words
vector<string> words;
string s;
while (cin>>s && s!= "quit") words.push_back(s);
sort(words.begin(), words.end());
vector<string>w2;
if (0<words.size()) {w2.push_back(words[0]);
for (int i=1; i<words.size(); ++i)
if(words[i-1]!=words[i])
w2.push_back(words[i]);
}
cout<< "found " << words.size()-w2.size()
<< " duplicates\n";
for (int i=0; i<w2.size(); ++i)
cout << w2[i] << "\n";
http://staff.ustc.edu.cn/~zlwang/
USTC AUTO
Chapter 5 Errors
编程中错误(bugs)是不可避免的 错误来源?
错误类型?
最小化错误 组织代码和数据
调试
测试
进行错误检查并产生合理的消息 输入数据有效性
函数参数
前置/后置条件
异常 – error()
int main()
{
try
{
// …
}
catch (out_of_range&) {
cerr << "oops – some vector " " index out of range\n";
}
catch (…) {
cerr << "oops – some exception\n";
}
return 0;
}
http://staff.ustc.edu.cn/~zlwang/
USTC AUTO
Chapter 6 Writing a Program
一个简单的桌面计算器程序
重复分析、设计和实现的过程
策略:开始一个小的,然后逐渐完善代码
使用伪代码
借助先前工作
表达式语法
分析函数
Token 类型
程序组织 谁调用谁?
反馈的重要性
double primary() // Num or ‘(‘ Expr ‘)’
{
Token t = get_token();
switch (t.kind) {
case '(': // handle ‘(’expression ‘)’
{ double d = expression();
t = get_token();
if (t.kind != ')') error("')' expected");
return d;
}
case '8': // ‘8’ represents number “kind”
return t.value; // return value
default:
error("primary expected");
}
}
http://staff.ustc.edu.cn/~zlwang/
USTC AUTO
Chapter 7 Completing a Program
Token 类型定义 数据成员
构造函数
Token_stream 类型定义 函数成员
流概念
“增长”功能 eg. 提示符和错误恢复
消除“魔数”常量
class Token_stream {
bool full; // is there a Token in the buffer?
Token buffer; // here is where we keep a Token
public:
Token get(); // get a Token
void putback(Token); // put back a Token
// the buffer starts empty:
Token_stream() :full(false), buffer(0) { }
};
void Token_stream::putback(Token t)
{
if (full) error("putback() into a full buffer");
buffer=t;
full=true;
}
http://staff.ustc.edu.cn/~zlwang/
USTC AUTO
Chapter 8 Functions
声明和定义
头文件和预处理
作用域 全局、类、局部、语句
函数
调用 传值
传引用
传 const引用
名字空间 限制符:: 和 using
namespace Jack {// in Jack’s header file
class Glob{ /*…*/ };
class Widget{ /*…*/ };
}
#include "jack.h"; // this is in your code
#include "jill.h"; // so is this
void my_func(Jack::Widget p)
{ // OK, Jack’s Widget class will not
// clash with a different Widget
// …
}
http://staff.ustc.edu.cn/~zlwang/
USTC AUTO
Chapter 9 Classes
用户自定义类型 Class和 struct
private和 public 成员
• 接口
const成员
构造/析构
操作符重载
辅助函数
枚举 enum
Date 类型
// simple Date (use Month type)
class Date {
public:
enum Month {
jan=1, feb, mar, apr, may, jun, jul,
aug, sep, oct, nov, dec
};
Date(int y, Month m, int d); // check for valid // date and initialize
// …
private:
int y; // year
Month m;
int d; // day
};
Date my_birthday(1950, 30, Date::dec); // error: // 2nd argument not a Month
http://staff.ustc.edu.cn/~zlwang/
USTC AUTO
Chapter 10 Streams
设备、设备驱动、库、我们的代码
流模型 类型安全、缓冲
操作符 <<和 >>
文件类型 输入输出的打开
错误处理• 检查流状态
逻辑分离的代码作为独立的函数
参数化函数
为 Date 类型定义 >>
struct Reading { // a temperature reading
int hour; // hour after midnight [0:23]
double temperature;
Reading(int h, double t) :hour(h), temperature(t) { }
};
string name;
cin >> name;
ifstream ist(name.c_str());
vector<Reading> temps; // vector of readings
int hour;
double temperature;
while (ist >> hour >> temperature) { // read
if (hour < 0 || 23 <hour)
error("hour out of range");
temps.push_back( Reading(hour,temperature) ); // store
}
http://staff.ustc.edu.cn/~zlwang/
USTC AUTO
Chapter 11 Customizing I/O
格式化输出— int和double 的操纵符
文件打开模式
文本 vs 二进制文件
文件流中的定位
stringstreams
行和 char的输入输出
字符分类函数
double str_to_double(string s)
// if possible, convert characters
// in s to floating-point value
{
istringstream is(s); // make a stream double d;
is >> d;
if (!is) error("double format error");
return d;
}
double d1 = str_to_double("12.4"); // testing
double d2 = str_to_double("1.34e-3");
// will call error():
double d3 = str_to_double("twelve point four");
http://staff.ustc.edu.cn/~zlwang/
USTC AUTO
Chapter 12 Graphics
为什么需要Graphics/GUI?
WYSIWYG
显示模型 创建一个窗口
创建形状
Attach 对象
绘制功能
2D Graphics/GUI 库
FLTK
分层架构
接口类
int main()
{
using namespace Graph_lib; // use graph library
Point tl(100,200); // a point (obviously)
Simple_window win(tl,600,400,"Canvas"); Polygon poly; // make a polygon shape
poly.add(Point(300,200)); // add three points
poly.add(Point(350,100));
poly.add(Point(400,200));
poly.set_color(Color::red); // make it red
win.attach(poly); // connect poly to the window
win.wait_for_button(); // give up control
}
Window
Simple_window
Shape
Lines Polygon Rectangle Text
Point
Color Line_style
Line …
http://staff.ustc.edu.cn/~zlwang/
USTC AUTO
Chapter 13 Graphics Classes
代码组织
Point, Line,Color,
Line_style, Polylines,
Text, etc. 等类的实现
面向对象程序设计
Simple_window win20(pt,600,400,"16*16 color matrix");
Vector_ref<Rectangle> vr; // use like vector
// but imagine that it holds references to objects
for (int i = 0; i<16; ++i) { // i is the horizontal
// coordinate
for (int j = 0; j<16; ++j) { // j is the vertical
// coordinate
vr.push_back(
new Rectangle( Point(i*20,j*20),20,20)
);
vr[vr.size()-1].set_fill_color(i*16+j);
win20.attach(vr[vr.size()-1]);
}
// Graphing interface:
struct Point { … };
…
// window interface:
class Window {…};
…
FLTK headers
Graph codeWindow code
FLTK code
chapter12.cp
p:
Window.
h:
Window.c
pp:
#include "Graph.h"
#include "Window.h"
int main() { … }
Graph.cpp:
Graph.
h:
struct Point { … };
// GUI interface:
struct In_box { … };
…
GUI code
GUI.cp
p:
http://staff.ustc.edu.cn/~zlwang/
USTC AUTO
Chapter 14: Design Principles for Programming a
Class Library
实现应用领域使用的类型
派生类继承一些关键的抽象
提供最小个数的操作和访问函数
使用一致规范化的风格、合理地命名
只暴露接口 封装
虚函数 动态分配—多态
void Shape::draw() const
// The real heart of class Shape
// called by Window (only)
{
Fl_Color oldc = fl_color(); // save old color
// there is no good portable way of
// retrieving the current style (sigh!)
fl_color(line_color.as_int()); // set color and // style
fl_line_style(ls.style(),ls.width());
// call the appropriate draw_lines():
draw_lines(); // a “virtual call”
// here is what is specific for a // “derived class” is done
fl_color(oldc); // reset color to previous
fl_line_style(0); // (re)set style to default
}
http://staff.ustc.edu.cn/~zlwang/
USTC AUTO
Chapter 15 Graphing
图形化函数
标签、颜色的使用
缩放
typedef
标准数学函数
函数近似
近似误差
图形化数据
Function::Function( Fct f,double r1, double r2, //rangePoint xy, // screen location of (0, 0)int count, // number of pointsdouble xscale, // location (x,f(x)) is double yscale // (xscale*x,yscale*f(x)) )
{if (r2-r1<=0)
error("bad graphing range");if (count <=0)
error("non-positive graphing count");double dist = (r2-r1)/count;double r = r1;for (int i = 0; i<count; ++i) {
add(Point(xy.x+int(r*xscale), xy.y-int(f(r)*yscale)));
r += dist;}
}
http://staff.ustc.edu.cn/~zlwang/
USTC AUTO
Chapter 16 GUI
图形化 I/O
分层架构
反转控制 回调
等待循环
面向事件的动作
Buttons
Input/output 框
Button start_button(Point(20,20), 100, 20, "START", cb_start);
…
static void cb_start(Address, Address addr) { reference_to<Window>(addr).start();
}
void start(void) { start_pushed = true; }
….
void wait_for_start(void){
while (!start_pushed) Fl::wait();
start_pushed = false;
Fl::redraw();
}
….
Window win (Point(10,10), “My Window");
….
win.wait_for_start();
http://staff.ustc.edu.cn/~zlwang/
USTC AUTO
Chapter 17 Free Store
建立 vector 类型
指针类型
new操作符在自由存储(堆存储)上分配一个对象
为什么要使用自由存储?
运行时内存组织
数组索引
内存泄漏
void*
指针 vs 引用
class vector {
int sz; // the size
double* elem; // a pointer to the elements
public:
// constructor (allocate elements):
vector(int s) :sz(s), elem(new double[s]) { }
// destructor (deallocate elements):
~vector() { delete[ ] elem; }
// read access:
double get(int n) { return elem[n]; }
// write access:
void set(int n, double v) { elem[n]=v; }
// the current size:
int size() const { return sz; }
};
vector v(10);
for (int i=0; i<v.size(); ++i) {
v.set(i,i); cout << v.get(i) << ' ';
}
http://staff.ustc.edu.cn/~zlwang/
USTC AUTO
Chapter 18 Arrays
向量拷贝构造函数
向量拷贝赋值函数
浅拷贝和深拷贝
数组——尽量避免使用
重载 [ ]
i.e. 为 vector 定义 []
class vector {
int sz; // the size
double* elem; // pointer to elements
public:
// constructor:
vector(int s) :sz(s), elem(new double[s]) { }
// …
// read and write access: return a reference:
double& operator[ ](int n) { return elem[n]; }
};
vector v(10);
for (int i=0; i<v.size(); ++i) { // works and // looks right!
v[i] = i; // v[i] returns a // reference to the ith element
cout << v[i];
}
http://staff.ustc.edu.cn/~zlwang/
USTC AUTO
Chapter 19 Vector
改变 vector大小
改变表示方式来保护space 空间
添加
reserve(int n),
resize(int n),
push_back(double d)
this指针
优化拷贝赋值函数
模板
范围检查
异常处理
// an almost real vector of Ts:
template<class T> class vector { // “for all types T” int sz; // the size
T* elem; // a pointer to the elements
int space; // size+free_space
public:
// default constructor:
vector() : sz(0), elem(0), space(0);
// constructor:
explicit vector(int s)
:sz(s), elem(new T[s]), space(s) {
// copy constructor:
vector(const vector&);
// copy assignment:
vector& operator=(const vector&);
~vector() { delete[ ] elem; } // destructor
// access: return reference
T& operator[ ] (int n) { return elem[n]; }
int size() const { return sz; } // the current size
// …
};
http://staff.ustc.edu.cn/~zlwang/
USTC AUTO
Chapter 20 The STL
泛型编程 “提炼一个算法”
标准模板库 STL
60 个算法
sort, find, search, copy, …
vector, list, map, hash_map,…
10 个容器
迭代器定义了一个序列
函数对象
// Concrete STL-style code for a more
// general version of summing values
template<class Iter, class T> // Iter should be an // Input_iterator
// T should be // something we can // + and =
T sum(Iter first, Iter last, T s) // T is the // “accumulator type”
{
while (first!=last) {
s = s + *first;
++first;
}
return s;
}
iterators
http://staff.ustc.edu.cn/~zlwang/