C++ 面向对象高级编程 (上) week 1 (Boolan)

课程目标

  • 以良好的方式编写C++ class
    (Object Based: 面对的是单一class的设计)
    • class without pointer members -- Complex (week 1)
    • class with pointer members -- String
  • 学习Classes之间的关系
    (Object Oriented: 面对的是多重classes的设计, classes和classes之间的关系)
    • 继承 (inheritance)
    • 复合 (composition)
    • 委托 (delegation)

推荐书目

  1. C++ Primer (5th Edition) by Stanley B. Lippman
  2. The C++ Programming Language (4th Edition) by Bjarne Stroustrup
  3. Effective C++: 55 Specific Ways to Improve Your Programs and Designs (3rd Edition) by Scott Meyers
  4. The C++ Standard Library - A Tutorial and Reference (2nd Edition) by Nicolai M. Josuttis
  5. STL源码剖析 by 侯捷

点评: 选择一本好的C++书籍(1和2两本书皆可), 然后以及尽量多的完成书籍的习题,可以帮助完成C++语法的学习; 熟悉C++的语法后,通过3学习如何正确高效地使用C++; 如果对STL的一些实现有兴趣,可参考书目4和5.

复数Complex类的设计

主程序complex-test.cpp:

#include <iostream>
#include "complex.h"
using namespace std;

int main() {
  complex c1(2, 1);
  complex c2;
  cout << c1 << endl;
  cout << c2 << endl;

  // ...
  return 0; 
}

头文件complex.h的布局:

#ifndef __COMPLEX__  // use guard against multiple inclusion
#define __COMPLEX__
// forward declaration (前置声明)
// class declaration (类-声明)
// class definition (类-定义)
#endif  // __COMPLEX__

关于guard (防御式申明) (摘自C++ Primer):

C++ programs use the preprocessor to define header guards. Header guards rely on preprocessor variables. Preprocessor variables have one of two possible states: defined or not defined. The #define directive takes a name and defines that name as a preprocessor variable. There are two other directives that test whether a given preprocessor variable has or has not been defined: #ifdef is true if the variable has been defined, and #ifndef is true if the variable has not been defined. If the test is true, then everything following the #ifdef or #ifndef is processed up to the matching #endif.

class的声明(declaration)和定义(definition)

// class declaration (类-声明)
class complex {
public:
  complex (double r = 0, double i = 0): re (r), im (i) { }
  complex& operator += (const complex&);
  double real () const { return re; }
  double imag () const { return im; }
private:
  double re, im;
  friend complex& __doapl (complex *, const complex&);
};

有些函数(e.g., constructor, real, imag)在此直接定义 (自动成为inline候选人), 另一些函数(e.g., operator+=, __doapl)在class body之外定义:

// class definition (类-定义)
inline complex&
__doapl (complex* ths, const complex& r)
{
  ths->re += r.re;
  ths->im += r.im;
  return *ths;
}

inline complex&
complex::operator += (const complex& r)
{
  return __doapl (this, r);
}

解释几个重要概念:

  • 关于inline(内联)函数 (摘自C++ Primer):

Classes often have small functions that can benefit from being inlined. Member functions defined inside the class are automatically inline. Thus, complex’s constructor and real()/imag() are inline by default. We can explicitly declare a member function as inline as part of its declaration inside the class body. Alternatively, we can specify inline on the function definition that appears outside the class body.

Although we are not required to do so, it is legal to specify inline on both the declaration and the definition. However, specifying inline only on the definition outside the class can make the class easier to read.

  • 关于access level (访问级别) (摘自C++ Primer):

In C++ we use access specifiers to enforce encapsulation:

  • Members defined after a public specifier are accessible to all parts of the program. The public members define the interface to the class.
  • Members defined after a private specifier are accessible to the member functions of the class but are not accessible to code that uses the class. The private sections encapsulate (i.e., hide) the implementation.

A class may contain zero or more access specifiers, and there are no restrictions on how often an access specifier may appear. Each access specifier specifies the access level of the succeeding members. The specified access level remains in effect until the next access specifier or the end of the class body.

  • 关于constructor (构造函数)
// within the complex class declaration
complex (double r = 0, double i = 0)
  : re (r), im (i)  // initializer list 
{ }

摘自C++ Primer:

Each class defines how objects of its type can be initialized. Classes control object initialization by defining one or more special member functions known as constructors. The job of a constructor is to initialize the data members of a class object. A constructor is run whenever an object of a class type is created.
constructor initializer list specifies initial values for one or more data members of the object being created. The constructor initializer is a list of member names, each of which is followed by that member’s initial value in parentheses (or inside curly braces). Multiple member initializations are separated by commas.

  • 关于const member function (常量成员函数)
// within the complex class declaration
double real () const { return re; }
double imag () const { return im; }

// inside main()
const  complex c1(2, 1);
cout << c1.real();  // okay
cout << c2.imag();  // okay

摘自C++ Primer:

A const following the parameter list indicates that this is a pointer to const. Member functions that use const in this way are const member functions.
Objects that are const, and references or pointers to const objects, may call only const member functions.

  • 关于 friend (友元) (摘自C++ Primer):

A class can allow another class or function to access its nonpublic members by making that class or function a friend. A class makes a function its friend by including a declaration for that function preceded by the keyword friend.
Ordinarily it is a good idea to group friend declarations together at the beginning or end of the class definition.

  • 关于operator overloading (操作符重载) (摘自C++ Primer):

Overloaded operators are functions with special names: the keyword operator followed by the symbol for the operator being defined. Like any other function, an overloaded operator has a return type, a parameter list, and a body.
An overloaded operator function has the same number of parameters as the operator has operands. A unary operator has one parameter; a binary operator has two. In a binary operator, the left-hand operand is passed to the first parameter and the right-hand operand to the second. Except for the overloaded function-call operator, operator(), an overloaded operator may not have default arguments.
If an operator function is a member function, the first (left-hand) operand is bound to the implicit this pointer. Because the first operand is implicitly bound to this, a member operator function has one less (explicit) parameter than the operator has operands.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 203,772评论 6 477
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,458评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 150,610评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,640评论 1 276
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,657评论 5 365
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,590评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,962评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,631评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,870评论 1 297
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,611评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,704评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,386评论 4 319
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,969评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,944评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,179评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 44,742评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,440评论 2 342

推荐阅读更多精彩内容