C++ primer4 Chapter 7. Functions

1, inline 函数避免函数调用的开销,将函数指定为 inline 函数,(通常)就是将它在程序中每个调用点上“内联地”展开。

       // inline version: find longer of two strings
       inline const string &
       shorterString(const string &s1, const string &s2)
       {
               return s1.size() < s2.size() ? s1 : s2;
       }

2,把 inline 函数的定义放在头文件中 ,可以确保在调用函数时所使用的定义是相同的,并且保证在调用点该函数的定义对编译器可见。

 

3,每个成员函数都有一个额外的、隐含的形参 this。在调用成员函数时,形参 this 初始化为调用函数的对象的地址。为了理解成员函数的调用,可考虑下面的语句:

          bool same_isbn(const Sales_item &rhs) const
         { return isbn == rhs.isbn; }
       // pseudo-code illustration of how a call to a member function is translated
        Sales_item::same_isbn(&total, trans);
     可以理解跟在 Sales_item 成员函数声明的形参表后面的 const 所起的作用了:const 改变了隐含的 this 形参的类型。在调用 total.same_isbn(trans) 时,隐含的 this 形参将是一个指向 total 对象的 const Sales_Item* 类型的指针。

 

4, 函数指针是指指向函数而非指向对象的指针。像其他指针一样,函数指针也指向某个特定的类型。函数类型由其返回类型以及形参表确定,而与函数名无关:

               bool (*pf)(const string &, const string &);

      函数指针类型相当地冗长。使用 typedef 为指针类型定义同义词,可将函数指针的使用大大简化:

               typedef bool (*cmpFcn)(const string &, const string &);
              // compares lengths of two strings
             bool lengthCompare(const string &, const string &);

              cmpFcn pf1 = 0;             // ok: unbound pointer to function
              cmpFcn pf2 = lengthCompare; // ok: pointer type matches function's type
              pf1 = lengthCompare;        // ok: pointer type matches function's type
              pf2 = pf1;                  // ok: pointer types match

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值