小而美

导航

C++const限定符

在C语言中我们使用#define宏定义的方式来处理符号常量。而在C++中有一种更好的处理符号常量的方法,那就是使用const关键字来修改变量声明和初始化。这种处理常量方式的好处不言而喻:如果程序在多处需要使用同一个值时,我们不妨将这个值定义为常量,这样在需要修改值时,只需修改常量即可,省去很多麻烦。

另外相比于C语言的宏定义方式,const限定符的优点在于:1、能够明确指定类型;2、可以使用C++的作用域规定将定义限定在特定的函数或文件中。以下代码:

#include<iostream>
#include<string>
#define mon 'c'
#define mos 1.5
#define mom "ch"
#define MAX 100000000
int main()
{
    using std::cout;
    using std::endl;
    using std::string;

    const int Month = 12;
    const char Char = 'c';
    string Str = "hello";
    cout<<Month<<endl;
    cout<<Str<<endl;
    cout<<Char<<endl;
    cout<<mon<<endl<<MAX<<endl;

    return 0;
}

posted on 2015-04-18 20:11  小而美  阅读(140)  评论(0)    收藏  举报