C++ 面向?qū)ο蟾呒?jí)編程 (上) week 1 (Boolan)

課程目標(biāo)

  • 以良好的方式編寫(xiě)C++ class
    (Object Based: 面對(duì)的是單一class的設(shè)計(jì))
    • class without pointer members -- Complex (week 1)
    • class with pointer members -- String
  • 學(xué)習(xí)Classes之間的關(guān)系
    (Object Oriented: 面對(duì)的是多重classes的設(shè)計(jì), classes和classes之間的關(guān)系)
    • 繼承 (inheritance)
    • 復(fù)合 (composition)
    • 委托 (delegation)

推薦書(shū)目

  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 侯捷

點(diǎn)評(píng): 選擇一本好的C++書(shū)籍(1和2兩本書(shū)皆可), 然后以及盡量多的完成書(shū)籍的習(xí)題,可以幫助完成C++語(yǔ)法的學(xué)習(xí); 熟悉C++的語(yǔ)法后,通過(guò)3學(xué)習(xí)如何正確高效地使用C++; 如果對(duì)STL的一些實(shí)現(xiàn)有興趣,可參考書(shū)目4和5.

復(fù)數(shù)Complex類(lèi)的設(shè)計(jì)

主程序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 (類(lèi)-聲明)
// class definition (類(lèi)-定義)
#endif  // __COMPLEX__

關(guān)于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 (類(lèi)-聲明)
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&);
};

有些函數(shù)(e.g., constructor, real, imag)在此直接定義 (自動(dòng)成為inline候選人), 另一些函數(shù)(e.g., operator+=, __doapl)在class body之外定義:

// class definition (類(lèi)-定義)
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);
}

解釋幾個(gè)重要概念:

  • 關(guān)于inline(內(nèi)聯(lián))函數(shù) (摘自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.

  • 關(guān)于access level (訪問(wèn)級(jí)別) (摘自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.

  • 關(guān)于constructor (構(gòu)造函數(shù))
// 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.

  • 關(guān)于const member function (常量成員函數(shù))
// 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.

  • 關(guān)于 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.

  • 關(guān)于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.

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末映企,一起剝皮案震驚了整個(gè)濱河市悟狱,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌堰氓,老刑警劉巖挤渐,帶你破解...
    沈念sama閱讀 218,451評(píng)論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異双絮,居然都是意外死亡浴麻,警方通過(guò)查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,172評(píng)論 3 394
  • 文/潘曉璐 我一進(jìn)店門(mén)囤攀,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)软免,“玉大人,你說(shuō)我怎么就攤上這事焚挠「嘞簦” “怎么了?”我有些...
    開(kāi)封第一講書(shū)人閱讀 164,782評(píng)論 0 354
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)榛泛。 經(jīng)常有香客問(wèn)我蝌蹂,道長(zhǎng),這世上最難降的妖魔是什么挟鸠? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,709評(píng)論 1 294
  • 正文 為了忘掉前任叉信,我火速辦了婚禮,結(jié)果婚禮上艘希,老公的妹妹穿的比我還像新娘硼身。我一直安慰自己,他們只是感情好覆享,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,733評(píng)論 6 392
  • 文/花漫 我一把揭開(kāi)白布佳遂。 她就那樣靜靜地躺著,像睡著了一般撒顿。 火紅的嫁衣襯著肌膚如雪丑罪。 梳的紋絲不亂的頭發(fā)上,一...
    開(kāi)封第一講書(shū)人閱讀 51,578評(píng)論 1 305
  • 那天凤壁,我揣著相機(jī)與錄音吩屹,去河邊找鬼。 笑死拧抖,一個(gè)胖子當(dāng)著我的面吹牛煤搜,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播唧席,決...
    沈念sama閱讀 40,320評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼擦盾,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來(lái)了淌哟?” 一聲冷哼從身側(cè)響起迹卢,我...
    開(kāi)封第一講書(shū)人閱讀 39,241評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎徒仓,沒(méi)想到半個(gè)月后腐碱,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,686評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡掉弛,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,878評(píng)論 3 336
  • 正文 我和宋清朗相戀三年喻杈,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片狰晚。...
    茶點(diǎn)故事閱讀 39,992評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖缴啡,靈堂內(nèi)的尸體忽然破棺而出壁晒,到底是詐尸還是另有隱情,我是刑警寧澤业栅,帶...
    沈念sama閱讀 35,715評(píng)論 5 346
  • 正文 年R本政府宣布秒咐,位于F島的核電站谬晕,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏携取。R本人自食惡果不足惜攒钳,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,336評(píng)論 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望雷滋。 院中可真熱鬧不撑,春花似錦、人聲如沸晤斩。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 31,912評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)澳泵。三九已至实愚,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間兔辅,已是汗流浹背腊敲。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 33,040評(píng)論 1 270
  • 我被黑心中介騙來(lái)泰國(guó)打工, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留维苔,地道東北人碰辅。 一個(gè)月前我還...
    沈念sama閱讀 48,173評(píng)論 3 370
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像蕉鸳,于是被迫代替她去往敵國(guó)和親乎赴。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,947評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容