### C++总结-[类成员函数]
生活随笔
收集整理的這篇文章主要介紹了
### C++总结-[类成员函数]
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
C++類中的常見函數(shù)。
#@author: gr #@date: 2015-07-23 #@email: forgerui@gmail.com一、constructor, copy constructor, copy assignment, destructor
1. copy constructor必須傳引用,傳值編譯器會報錯
2. operator= 返回值為引用,為了連續(xù)賦值
3. operator=需要進(jìn)行自賦值判斷
4. copy constructor, operator= 都需要調(diào)用子類的相應(yīng)拷貝函數(shù)
5. operator=可以用copy constructor構(gòu)造一個臨時對象保存副本
6. destructor如果是基類,應(yīng)該聲明virtual
7. copy constructor對傳進(jìn)來的同類型對象的私有成員也有訪問權(quán)限
private的限定符是編譯器限定的,因?yàn)樵陬惡瘮?shù)中,類私有成員變量是可見的,所以可以訪問同類型私有成員。這個性質(zhì)是針對所有類成員函數(shù),不局限于構(gòu)造函數(shù)。
class Widget { private:char* name;int weight;static int counts; //需要在類外進(jìn)行初始化 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) { //參數(shù)是引用類型++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; //將被析構(gòu)釋放name = pName;++counts;return *this; //返回引用}virtual ~Widget() { //基類析構(gòu)聲明為虛函數(shù)--counts; //靜態(tài)變量減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); //調(diào)用子類return *this; //返回引用}~Television() {} };二、operator+,operator+=
1. operator+需要返回const值傳遞
2. operator+= 需要返回引用,可以進(jìn)行連續(xù)賦值
3. operator+ 可以調(diào)用operator+=實(shí)現(xiàn)
class Widget{ public:const Widget operator+ (const Widget& lhs) { //返回const值Widget tempWidget(*this);tempWidget += lhs; //調(diào)用+=實(shí)現(xiàn)return tempWidget;} Widget& operator+= (const Widget& lhs) { //返回引用weight += lhs.weight;return *this;} };三、operator++ 前置、后置
1. 前置方式要返回引用
2. 后置方式返回值const,避免a++++形式出現(xiàn)
3. 為了區(qū)分兩者,后置方式加一個int參數(shù)
4. 后置方式調(diào)用前置方式實(shí)現(xiàn)
class Widget { public:const Widget operator++(int) { //返回const值,添加一個int參數(shù)Widget tempWidget(*this);++*this; //調(diào)用++實(shí)現(xiàn)return tempWidget;}Widget& operator++() { //返回引用weight++; return *this;} };四、operator()
operator()一般可以實(shí)現(xiàn)函數(shù)對象,還可以用來模擬實(shí)現(xiàn)Matrix的元素獲取。
函數(shù)對象需要實(shí)現(xiàn)operator(),使一個對象表現(xiàn)得像一個函數(shù)。
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形式像函數(shù) std::cout << Compare(a, b) ? "a < b" : "a >= b" << std::endl;轉(zhuǎn)載于:https://www.cnblogs.com/gr-nick/p/4753133.html
總結(jié)
以上是生活随笔為你收集整理的### C++总结-[类成员函数]的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 天马:明年量产折叠屏 全力攻关AMOLE
- 下一篇: spring -mvc 将对象封装jso