尽量不要使用#define,而是用const、enum、inline替换。


出处:http://www.cnblogs.com/couhujia/archive/2012/10/20/2732071.html

 为什么这么说呢?或许很多程序员已经习惯在文件开始使用大量的#define语句。例如:这里程序文件开头有如下#define语句

        #define     N                     10
        #define     PI                     3.14
        #define     MAX                10000
        #define     Heigth               6.65
        ...
        ...
        假设这里程序运行出错误,而且就是在我们使用这些常量有错误,此时编辑器应该会抛出错误信息。如果该信息提示6.65这里有错误,Ok如果你运气好你正好记得或者程序简单一眼能找到6.65表示什么,如果程序很复杂,而且报出6.65的文件是引用该文件,不记得,那么你会困惑这是什么?或许会花大量时间去追踪6.65是什么?进而定位问题。
        为什么错误信息是6.65呢?而不是Heith呢?因为在预编译阶段,已经用5.65来代替Heigth,Height没有进入记号表(system table)内。解决之道是可以使用下面语句进行替换
         const double treeHeight=5.68;
    作为一个语言常量,treeHeight肯定会被编译器获知,并且进入记号表内。报出的错误不在是数字而是变量名称,这样有利于定位问题。
        这里特别说明一下常量替换#define有两种特殊情况。
    第一个是定义常量指针。这里要将指针定义为常量指针,同时该指针也是指向一个常量,所以是下面的形式:
          const char * const HZ="Hang Zhou";
       在C++中最好使用string对象来替换掉char*形式:
          const std::string  HZ ("Hang Zhou");
       第二个值得注意的就是class专属常量。首先将作用于限制到类内,必须将其声明为其成员。其次确保此常量至多只有一份实体,必须让它称为static成员。例如:
复制代码
1         class People
2         {
3             private:
4                     static const int Number=10;
5                     int phoneNumbers[Number];
6             ......
7         }
复制代码
         这看到的是声明式,而非定义式。通常C++要求你对使用的任何东西提供一个定义式。 或者使用enum,对于形式函数的宏,尽可能用inline或者template来代替。但是如果它是个class专属常量又是static且为整数类型(int,char,bool)则需特殊处理。只要不娶它们地址,则只用声明而不用提供定义式子。但是如果取class专属常量地址,纵使不取其地址编译器就要你提供定义式子。
         static const int People::Number
        这里定义不设初始值,是因为声明的时候已经获取了初值。
        这里可以使用enum完成类似的功能
        class People
        {
            private:
                    enum { Number = 10 };
                    int phoneNumbers[Number];
            ....
        }
        enum比较像#define而不像const。因为取const的地址是合法的,取一个enum的地址就不合法,取#define地址通常就不合法。所以可以通过enum来实现不让他人取得某个常量的地址。
        下面介绍一道笔试题目
           #define PRODUCT(a,b) a*b
           ....
           int a=5,b=3,c;
          c=PRODUCT(a+3,b+4);
        那么c的值为多少?c=5+3*3+4=18而不是程序员预想的56,如果想达到预期的结果必须这样写
          #define PRODUCT(a,b) ((a)*(b))
        或许这样你还会坚持会写宏函数,因为你想说只用写一个宏函数就能完成int,flaot,double等类型的乘积运算。那么在看看下面例子
         #define MAX(a,b) ((a)>(b)?(a):(b))
         int a=5,b=3
         MAX(++a,b);   //a被加了两次
         MAX(++a,b+4);  //a被加了一次
        a被加的结果可能不是预期的,完全可以用template inline函数达到宏的预期效果,并且效率与宏差不多。
1         template<typename T>
2         inline void Max(const T& a,const T& b)
3         {
4             f(a>b?a:b);
5         }
 
        inline函数是一种编译机制,有点从代码上是看不出来的,但是从程序的执行效率上有差别,通常编译器对函数调用的处理是一种类似中断的方式,即当执行到函数调用语句时,会将当前所有信息存储到寄存器中,在去执行函数的代码,执行完后取回寄存器值,恢复到调用函数开始的状态,继续执行代码。声明为   inline 函数后,编译器不把函数编译成调用函数而是将代码拷贝到被调用的地方。所以效率上要比普通函数高一些,少了存寄存器与取寄存器信息的步骤。
        另外需要注意的是inline函数最好写到.h文件中去,或者直接写到类中去。
        const允许程序员指定一个语义约束,即不能被改动,编译器会强制实施这项约束。它表示被它修饰的值是不变的。const可以在classes外部修饰global或namespace作用域中的常量,或修饰文件、函数或者static对象以及指针。在const应用在指针中要注意关键字const出现在“*”的什么地方,如果在左边表示被指向的值是常量,如果在右边表示指针自身是常量。出现两边表示两者的功能的并集。这里特别说以下几点:
        (1)迭代器中的cosnt
        const std::vector<int>::iterator iter=vec.begin();  //相当于iter不能改变
        std::vector<int>::const_iterator citer=vec.begin();  //iter所指向的内容无法改变
        (2) 将函数返回值声明为常量,不仅可以降低因程序员错误造成的不可预料的情况,并且不用放弃安全性和高效性。例如:
         const operater *(const &lhs,const &rhs);
         if((a * b  = c);//本意是if(a*b==c)因程序员马虎而写成这样
        如果a和b都是内置类型,此代码就不合理,但是是我们自定义类型,就可能行得通,如果声明返回值是cosnt,就可以预防这么做了。
       (3)const成员函数,它是为了确认成员函数可作用于const对象。而且两个成员函数如果只是常量性不同,是可以重载的。成员函数后面跟const,表示该函数不能更改类的成员变量(下面有代码验证,如果尝试对其成员赋值,编译器会爆出错误)。原理就是编译器将其认为是只读变量。并且大多数const对象用于引用传递或者指针传递。
复制代码
 1 #include <iostream>
 2 #include <string>
 3 
 4 class People
 5 {
 6     public:
 7          People():m_sName(""),m_iAge(0){}
 8          People(std::string name,int age):m_sName(name),m_iAge(age){}
 9          void set(int age)
10          {
11             this->m_iAge=age;
12          }
13          
14          void set2(int age) const
15          {
16             this->m_iAge=age;
17          }
18          
19          int get()
20          {
21             return this->m_iAge;
22          }
23     private:
24          std::string m_sName;
25          int m_iAge;
26 };
27 
28 int main(int argc,char **argv)
29 {
30     People* p=new People("sky",8);
31     p->set(10);
32     std::cout<<p->get()<<std::endl;
33     p->set2(12);
34     std::cout<<p->get()<<std::endl;
35     delete p;
36     return 0;
37 }
复制代码
编译该文件会报以下错误信息
const_test.cpp: In member function `void People::set2(int) const':
const_test.cpp:16: error: assignment of data-member `People::m_iAge' in read-only structure
const_test.cpp:36:2: warning: no newline at end of file
cosnt重载(注意:仅当形参是引用或者指针时候,形参是否为const才会有影响)。可以试一试我们将下面代码的&去掉,传入const_int其实调用的是void set(int age)函数,说明形参的const是没有起作用的下面是验证代码
复制代码
 1 #include <iostream>
 2 #include <string>
 3 
 4 class People
 5 {
 6     public:
 7          People():m_sName(""),m_iAge(0){}
 8          People(std::string name,int age):m_sName(name),m_iAge(age){}
 9          void set(const int& age) const
10          {
11              std::cout<<"this is const"<<std::endl;
12          }
13          
14          void test(int& age)
15          {
16              std::cout<<"this is non-const"<<std::endl;
17          }
18          
19          void test(short age)
20          {
21              std::cout<<"this is non-const"<<std::endl;
22          }
23          
24          int get()
25          {
26             return this->m_iAge;
27          }
28     private:
29          std::string m_sName;
30          int m_iAge;
31 };
32 
33 int main(int argc,char **argv)
34 {
35     People* p=new People("sky",8);
36     const int const_int=12;
37     p->test(const_int);
38     std::cout<<p->get()<<std::endl;
39     delete p;
40 }
复制代码

(4)关于重载函数代码重复的问题。由经验可以得出我们通过const重载的函数往往有大量的代码是重复,甚至是一样的。如果大部分重复代码,我们可以将这些重复的代码写成一个函数,在由它们分别调用。如果是一样的,如下代码,我们就可以在non-const函数中调用const函数,来解决代码重复。

复制代码
 1 class People
 2 {
 3     public:
 4          People():m_sName(""),m_iAge(0){}
 5          People(std::string name,int age):m_sName(name),m_iAge(age){}
 6          void eat(const People & Person) const
 7          {
 8              std::cout<<"this person info is:{age ="<<Person.m_iAge()<<",name ="<<Person.m_sName()<<std::endl;
 9              std::cout<<"eating"<<std::endl;
10              std::cout<<"end"<<std::endl;
11          }
12          
13          void  eat ( People & Person)
14          {
15              std::cout<<"this person info is:{age ="<<Person.m_iAge()<<",name ="<<Person.m_sName()<<std::endl;
16              std::cout<<"eating"<<std::endl;
17              std::cout<<"end"<<std::endl;
18          }
19     private:
20          std::string m_sName;
21          int m_iAge;
22 };
复制代码

然后在non-const eat函数中首先将*this类型由People&显示的转化为const People&让其调用const函数,即函数重载

复制代码
 1 #include <iostream>
 2 #include <string>
 3 
 4 class People
 5 {
 6     public:
 7          People():m_sName(""),m_iAge(0){}
 8          People(std::string name,int age):m_sName(name),m_iAge(age){}
 9          void eat(const People & Person) const
10          {
11              std::cout<<"this person info is:{age ="<<Person.m_iAge<<",name ="<<Person.m_sName<<"}"<<std::endl;
12              std::cout<<"eating"<<std::endl;
13              std::cout<<"end"<<std::endl;
14          }
15          
16          void eat(People & Person)
17          {
18              static_cast<const People&>(*this).eat(Person);
19          }
20     private:
21          std::string m_sName;
22          int m_iAge;
23 };
24 
25 int main(int argc,char **argv)
26 {
27     People Person("sky",8);
28     Person.eat(Person);
29 }
复制代码

运行的结果为

this person info is:{age =8,name =sky
eating
end

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值