1.友元
- 友元類:可以訪問該類的私有成員;
Class Tv {
public:
friend class Romote; //Remote can access Tv private parts
...
}
class Romote {
...
void test(Tv & T) {
...
}
}
- 友元成員函數:只能通過友元成員函數訪問該類的私有成員;
class Tv; //前向聲明
class Remote {
...
};
class Tv {
friend void Remote::set_chan(Tv & t, int c); //友元成員函數,可以影響Tv的私有成員
...
private:
int channel;
};
//Remote methods as inline functions
...
inline Remote::set_chan(Tv & t, int c) {
t.channel = c;
}
- 互相友元類;
class Tv {
friend class Remote;
public:
void buzz(Remote & r);
...
};
class Remote {
friend class Tv;
...
};
inline void Tv::buzz(Remote & r) {
...
}
- 共同的友元;
class Analyzer;
class Probe {
friend void sync(Analyzer & a, const Probe &p); //sync a to p
friend void sync(Probe &p, const Analyzer & a); //sync p to a
...
};
class Analyzer{
friend void sync(Analyzer & a, const Probe &p); //sync a to p
friend void sync(Probe &p, const Analyzer & a); //sync p to a
...
};
//define
inline void sync(Analyzer & a, const Probe &p) {
...
}
inline void sync(Probe &p, const Analyzer & a) {
...
}
2.異常
- 可以使用abort()直接終止程序,或返回錯誤碼errno;
- 使用try-catch塊捕獲異常,throw拋出異常;
- catch(...){//statements},省略號表示可以捕獲任何異常;
- 基類對象可以捕獲派生類對象異常,但派生類對象只能捕獲派生類對象異常;
- exception類:頭文件stdexcept定義了logic_error和runtime_error類,logic_error系列包含domain_error,invalid_argument,length_error和out_of_bounds等類型錯誤,runtime_error包含range_error、overflow和underflow等類型錯誤。
try {
...
} catch(out_of_bounds & oe) { //catch out_of_bounds error
...
} catch(logic_error & oe) { //catch remaining logic_error family
...
} catch(exception & oe) { //catch runtime_error, exception objects
...
}
- 包含new頭文件,可以捕獲bad_alloc異常;
- 未捕獲異常和意外異常會導致調用terminate()接口,然後調用abort()終止程序;未捕獲異常可以使用set_terminate()指定終止操作,意外異常可以使用set_unexpected()函數指定終止操作, set_unexpected使用更嚴格,指定的函數只能通過terminate()/abort()/exit()來終止程序,或者拋出異常。
#include <exception>
void myQuit() {
...
exit(5);
}
set_terminate(myQuit);
void myUnexpected() {
throw std::bad_exception(); //or just throw
}
set_unexpected(myUnexpected);
3.強制類型轉換
- dynamic_cast:在類類型轉換中,只有類型相同或發生向上轉換(派生類轉換爲基類)時,才進行轉換,否則將返回空指針。
class A {
...
}
class B : public A {
...
}
A *a;
B *b;
A *t = dynamic_cast<A *> b; //valid
B *t = dynamic_cast<B*> a; //invalid, return null
- const_cast: 用於強制更改const變量,但是使用了const_cast會刪除const特徵,使得
- static_cast:
- reinterpret_cast:
4.其他
- typeid運算符:確定兩個對象是否未同種類型,同時typeid包含name()函數返回隨實現而異的字符串--類型,定義位於typeinfo頭文件中。
typeid(classname) == typeid(*pg);
cout << "Now processing type " << typeid(*pg).name() << endl;