C/C++ const总结

C/C++ const总结

一、常变量

const type arguement_name || type const arguement

const int a = 5;      //定义一个int型的常量,其值不能修改
const int b;          //定义const常量时必须初始化
b = 10;               //错误,const常量声明后不能进行初始化或修改

在类中声明const变量:

class Test
{
 private:
   const int a = 1;        //合理,在申明时初始化。
   const int b;            //合理,在类中申明可以暂时不初始化。
 public:
   Test(){}                //不合理,没有对const变量b进行初始化。
   Test():b(2){}           //合理,const变量均已初始化。
   Test():a(1), b(2){}     //合理,const变量均已初始化,并且在申明时初始化后还可以通过构造函                                数初始化列表修改。
   Test():{ a = 1; b = 2}  //不合理,只能通过构造函数初始化列表初始化。
}

二、常指针

const type * argue_ment || type * const arguement

int i = 100,j=200;          
const char *pb = &i;         //pb指向的值不能更改,但是可以更改pb的指向
*pb=300;                     //非法操作
pb = &j;                     //合法操作
char* const pc = &i          //不可以更改pc的指向,但是可以修改pc指向的值
pc = &j;                     //非法操作
*pc = 300;                   //合法操作

三、常引用

const type& arguement

引用为变量的别名,因此常引用比较简单,const修饰的引用不能修改其值,并且只有一种形式。

const int& i = 5;            //合法操作
int& const i = 5;            //非法操作,智能使用第一种形式

四、常成员函数

return_type class_name::function_name() const

teturn_type const class_name::funciton_name()

两种形式含义相同,const成员函数中禁止修改类种的所有数据成员,也不能调用类中非const成员函数来防止修改数据成员,例如: Test::display() const成员函数中不能调用 Test::add()非const成员函数(尽管add()没有修改数据成员)

五、常对象

const class_name object_name || class_name const object_name

C++中在定义对象时可以声明为const,当对象声明为const后,该对象的所有数据成员均不能被修改,不管是哪种形式,该对象就只能被const修饰的成员了(包括const成员变量和const成员函数),因为非const成员可能会修改对象的数据(编译器也会这样假设),C++金中支这样做。

class Test
{
  private:
      int a;
      int b;
  public:
      Test(){}
      Test(int x, int y): a(x), b(y){}
      void display() const;
      int add();
};
void Test::display() const
{
    std::cout << a << std::endl;
}
void Test::add()
{
    return a + b;
}
const Test s(1,2);
s.display();               //合理,display为const成员函数
int z = s.add();           //错误,add为非const成员函数,s无法调用
发布了48 篇原创文章 · 获赞 5 · 访问量 2602

猜你喜欢

转载自blog.csdn.net/Mr_robot_strange/article/details/104532715