1. class有兩種
- 不含有指針
- 含有指針
2. 基于對象 與 面向?qū)ο?/h4>
3. c++語言 與 c++標(biāo)準(zhǔn)庫
4. 頭文件的布局
#ifndef __COMPLEX__ (防止重復(fù)聲明)
#define __COMPLEX__
0.前置聲明(聲明后面要用到的類和全局函數(shù))
1.類聲明(class head, class body)
2.class body外面定義成員函數(shù),全局函數(shù)
#endif
5.一些細(xì)節(jié)
- 在class body內(nèi)部定義的是inline函數(shù),但只是給編譯器的建議,最終是否inline由編譯器決定。在函數(shù)定義的時候前面寫上inline。
-
訪問級別:public,private。數(shù)據(jù)和不對外使用的函數(shù)要聲明為私有的。
-
構(gòu)造函數(shù):函數(shù)名稱與類名相同,參數(shù)可以有默認(rèn)值,寫為初始化列表效率高(變量賦值兩個階段:初始化:re(r),im(i),賦值在{}中)。
構(gòu)造函數(shù)可以有多個,overloading(重載)。
構(gòu)造函數(shù)放在private區(qū),表示不能在外界創(chuàng)建對象,單例模式。
- 不帶指針的函數(shù)多半不用寫析構(gòu)函數(shù)。
- 函數(shù)() const {} 加const不改變數(shù)據(jù)內(nèi)容。
外界const對象只能調(diào)用const函數(shù),因為不加const修飾函數(shù),編譯器會認(rèn)為這個函數(shù)可能改變數(shù)據(jù),所以const對象不允許調(diào)用非const函數(shù)。
-
函數(shù)參數(shù)傳遞,pass by value VS. pass by reference (to const) 最好都傳引用,若變量只有1個或兩個字節(jié)傳值也可以。
-
函數(shù)返回值,return by value VS. return by reference (to const) 盡量都用引用。
函數(shù)中需要返回的結(jié)果放置的位置:
(1)放在函數(shù)內(nèi)部創(chuàng)建的對象(生命周期只在函數(shù)里)里,這時必須return by value。
(2)放在函數(shù)傳入的參數(shù)里,這時都可以return by reference。
-
friends(友元):可以訪問private成員。
-
相同class的各個objects互為friends。
例如.
class complex
{
public:
int func(const complex& param)
{ return param.re + param.im; }
private:
double re, im;
};
...
{
complex c1(2,1);
complex c2;
c2.func(c1);
}
-
操作符重載
(1)作為成員函數(shù) this作為函數(shù)參數(shù)可以隱藏。
__doapl( do assaignment plus )
return by reference 語法分析:傳遞者無需知道接收者是以reference形式接收。
eg. c2 += c1; c1是傳遞者,c2是接收者。
c3 += c2 += c1;
(2)作為非成員函數(shù)
返回值一定要是value,因為返回的必定是個local object。
臨時對象 定義
typename (..); 不需要寫對象名 eg. complex(..,..); , int(7);
ostream& operator << (ostream & os, const complex &x) //返回值可以改為&。
{
return os << '(' << real(x) << ',' << imag(x) << ')';
}
cout << c1 << conj(c1); 級聯(lián)輸出,所以返回不能是void.
#ifndef __COMPLEX__ (防止重復(fù)聲明)
#define __COMPLEX__
0.前置聲明(聲明后面要用到的類和全局函數(shù))
1.類聲明(class head, class body)
2.class body外面定義成員函數(shù),全局函數(shù)
#endif
構(gòu)造函數(shù)可以有多個,overloading(重載)。
構(gòu)造函數(shù)放在private區(qū),表示不能在外界創(chuàng)建對象,單例模式。
外界const對象只能調(diào)用const函數(shù),因為不加const修飾函數(shù),編譯器會認(rèn)為這個函數(shù)可能改變數(shù)據(jù),所以const對象不允許調(diào)用非const函數(shù)。
函數(shù)中需要返回的結(jié)果放置的位置:
(1)放在函數(shù)內(nèi)部創(chuàng)建的對象(生命周期只在函數(shù)里)里,這時必須return by value。
(2)放在函數(shù)傳入的參數(shù)里,這時都可以return by reference。
例如.
class complex
{
public:
int func(const complex& param)
{ return param.re + param.im; }
private:
double re, im;
};
...
{
complex c1(2,1);
complex c2;
c2.func(c1);
}
(1)作為成員函數(shù) this作為函數(shù)參數(shù)可以隱藏。
__doapl( do assaignment plus )
return by reference 語法分析:傳遞者無需知道接收者是以reference形式接收。
eg. c2 += c1; c1是傳遞者,c2是接收者。
c3 += c2 += c1;
(2)作為非成員函數(shù)
返回值一定要是value,因為返回的必定是個local object。
臨時對象 定義
typename (..); 不需要寫對象名 eg. complex(..,..); , int(7);
ostream& operator << (ostream & os, const complex &x) //返回值可以改為&。
{
return os << '(' << real(x) << ',' << imag(x) << ')';
}
cout << c1 << conj(c1); 級聯(lián)輸出,所以返回不能是void.