C++類中的常見函數。
#@author: gr
#@date: 2015-07-23
#@email: forgerui@gmail.com
一、constructor, copy constructor, copy assignment, destructor
1. copy constructor必須傳引用,傳值編譯器會報錯
2. operator= 返回值為引用,為了連續賦值
3. operator=需要進行自賦值判斷
4. copy constructor, operator= 都需要調用子類的相應拷貝函數
5. operator=可以用copy constructor構造一個臨時對象保存副本
6. destructor如果是基類,應該聲明virtual
7. copy constructor對傳進來的同類型對象的私有成員也有訪問權限
private
的限定符是編譯器限定的,因為在類函數中,類私有成員變量是可見的,所以可以訪問同類型私有成員。這個性質是針對所有類成員函數,不局限于構造函數。
class Widget {
private:char* name;int weight;static int counts; //需要在類外進行初始化
public:Widget(char* _name, int _weight) : name(new char[strlen(_name)+1]), weight(_weight) { //初始化列表++counts;strcpy(name, _name);}Widget(const Widget& lhs) : name(new char[strlen(lhs.name)+1]), weight(lhs.weight) { //參數是引用類型++counts;strcpy(name, lhs.name);}Widget& operator= (const Widget& lhs) {if (this == &lhs) {return *this;}Widget widTemp(lhs); //臨時對象char* pName = widTemp.name;widTemp.name = name; //將被析構釋放name = pName;++counts;return *this; //返回引用}virtual ~Widget() { //基類析構聲明為虛函數--counts; //靜態變量減1delete[] name; //釋放指針}
};class Television : public Widget {
private:int size;
public:Television(char* _name, int _weight, int _size) : Widget(_name, _weight), size(_size) {}Television(const Television& lhs) : Widget(lhs), size(lhs.size){}Television& operator= (const Television& lhs) {if (this == &lhs) { //判斷自賦值return *this;}size = lhs.size;Widget::operator=(lhs); //調用子類return *this; //返回引用}~Television() {}
};
二、operator+,operator+=
1. operator+需要返回const值傳遞
2. operator+= 需要返回引用,可以進行連續賦值
3. operator+ 可以調用operator+=實現
class Widget{
public:const Widget operator+ (const Widget& lhs) { //返回const值Widget tempWidget(*this);tempWidget += lhs; //調用+=實現return tempWidget;} Widget& operator+= (const Widget& lhs) { //返回引用weight += lhs.weight;return *this;}
};
三、operator++ 前置、后置
1. 前置方式要返回引用
2. 后置方式返回值const,避免a++++形式出現
3. 為了區分兩者,后置方式加一個int參數
4. 后置方式調用前置方式實現
class Widget {
public:const Widget operator++(int) { //返回const值,添加一個int參數Widget tempWidget(*this);++*this; //調用++實現return tempWidget;}Widget& operator++() { //返回引用weight++; return *this;}
};
四、operator()
operator()
一般可以實現函數對象,還可以用來模擬實現Matrix的元素獲取。
函數對象需要實現operator()
,使一個對象表現得像一個函數。
struct Compare: public binary_function<Widget, Widget, bool> {
public:bool operator() (const Widget& rhs, const Widget& lhs)const {return rhs.weight < lhs.weight;}
};Widget a("a", 1);
Widget b("b", 2);
//下面使用Compare形式像函數
std::cout << Compare(a, b) ? "a < b" : "a >= b" << std::endl;