《程序员面试宝典》第6章 宏和const

(一)用一个宏定义FIND求一个结构体struc里某个变量相对struc的偏移量

        {

        int a;

        char b[20];

        double cc;

        }

        FIND(student,a);   //0

        FIND(student,b);   //4

        FIND(student,cc);   //4+20

    

       解题:

             #define FIND(struc,e)   (size_t)&(((struc*)0)->e)

             其中(struc*)0表示将常量0强制转化为struc *型指针所指向的地址;

              &(((struc*)0)->e):取结构体(struc*)0成员e的地址。因该结构体的首地址是0,所以其实就是得到了成员e距离结构体首地址的偏移量。

             (size_t)是一种数据类型,最好定义为一种无符号型数据,一般为unsigned int ,便于不同系统之间之间移植。


(二)关于宏的考题

      【1】   #define Second_per_year   (60*60*24*365)UL         //UL为无符号长整型,以防整型数溢出 

      【2】   #define  MIN(A,B)   ((A)<=(B)?(A):(B))


(三)const 

       【1】用途:(1)可以定义const常量

                             (2)可以修饰函数的参数和返回值,甚至函数的定义体。被const修饰的东西都受到强制保护,可以防止意外的变动。





#include <iostream>
#include <iomanip>
using namespace std;
class C
{
public:
C(int i):m_Count(i){}
int incr() const
{
return ++m_Count;
}

int  decr() const
{
return --m_Count;
}
private:
mutable int m_Count;
};
int main()
{
C c1(0),c2(10);
for(int tmp,i=0;i<10;i++)
{
tmp=c1.incr();
cout<<setw(tmp)<<setfill(' ')<<tmp<<endl;


tmp=c2.decr();
cout<<setw(tmp)<<setfill(' ')<<tmp<<endl;
}
return 0;
}


在const成员函数中,用mutable修饰成员变量名后,就可以修改类的成员变量了

以下为上面的代码运行结果

《程序员面试宝典》第6章 宏和const_第1张图片









你可能感兴趣的:(《程序员面试宝典》第6章 宏和const)