c++ primer 閱讀 day13

  • 不要返回局部對象的引用或指針

  • 返回類累心的函數(shù)和調(diào)用運算符

  • 引用返回左值

  • 列表初始化返回值

  • 主函數(shù)main的返回值

  • 調(diào)用重載的函數(shù)

      (a). int calc(int,int);
        int calc(const int, const int);
        //定義一個整型函數(shù)calc,有兩個const int型形參,與上一個
        //定義等價,重復聲明
    
    (b). int get();
       double get();
       //定義一個double型函數(shù),聲明有問題,函數(shù)進行調(diào)用時,因為函數(shù)的形參
       //為空,編譯器無法判讀調(diào)用哪個函數(shù)
    
    (c). int *reset(int *);
       double *reset(double *); 
       //定義一個指針函數(shù),類型為double *,形參類型也是double *
    
  • 重載和作用域
    內(nèi)層將會隱蓋外層的函數(shù),只調(diào)用內(nèi)部函數(shù),函數(shù)名字查找發(fā)生在類型檢查之前。

  • 默認實參
    將多個形參設定為默認值,注意,如果第一個形參有默認值,那么后面的形參也必須要有默認值。
    默認實參聲明

  /*
練習6.54
編寫函數(shù)的聲明,令其接受兩個int形參并返回類型也是int;然后聲明一個vector對象,令其元素是指向該函數(shù)的指針。
int func(int a,int b);
typedef int (*pf)(int,int);
std::vector<pf> v;

int func(int,int);
using pFunc = decltype(func) *;
std::vector<pFunc> v1;

*/

#include <iostream>
#include <string>
#include <vector>
using std::vector;
using std::cout;

inline int f(const int,const int);
typedef decltype(f) fp;

inline int numAdd(const int n1,const int n2) {return n1+n2;}
inline int numSub(const int n1,const int n2) {return n1-n2;}
inline int numMul(const int n1,const int n2) {return n1*n2;}
inline int numDiv(const int n1,const int n2) {return n1/n2;}

vector<fp*> v{numAdd,numSub,numMul,numDiv};

int main()
{
    //
    // @brief Exercise 6.56
    // @note Call each element in the vector and print their result.
    //
    for(auto it = v.cbegin();it != v.cend();++it)
        cout <<(*it)(2,2)<<std::endl;

}

下面看第7章

?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容