C++中的"const"
不进行知识点的罗列,一个是因为记不住,再一个罗列知识对理解没有任何帮助
这是偶然在西湖边发现的一家店,因为比较喜欢宫崎骏,嘿嘿嘿

先贴代码:
主要涉及const修饰类对象,const修饰成员变量,const修饰成员函数, const修饰指针
#include <iostream>
/////////////////////////////////////////////
/*const对象默认作用域为当前所处作用域范围*/
/*因为const限定变量无法修改,所以要在声明时进行初始化赋值*/
const int tempGlobal = 10;
/*要使const变量可以在其他文件访问可以使用extern修饰*/
extern int tempExtGlobal = 20;
/////////////////////////////////////////////
//const在类对象中使用
class Demo
{
public:
Demo(/* Demo* const this */)
:tempConst(1),
tempPtrConst(tempPtr),
tempConstPtrConst(tempPtr)
{
std::cout<<"构造"<<std::endl;
this->set(2);
*tempPtr = 3;
tempConstPtr = tempPtr;
};
~Demo(/* Demo* const this */)
{
std::cout<<"析构"<<std::endl;
if(tempPtr!=nullptr)
{
delete tempPtr;
tempPtr = nullptr;
}
};
void set(int value)
{
temp = value;
};
void test()
{
};
int getTempConst() const
{
return tempConst;
};
int getTemp() const
{
return temp;
};
const int* getTempPtr() const
{
return tempPtr;
};
const int* getTempConstPtr() const
{
return tempConstPtr;
};
const int* getTempPtrConst() const
{
return tempPtrConst;
};
const int* getTempConstPtrConst() const//这是一个只读的方法,不能修改类中任何成员
{
return tempConstPtrConst;
};
private:
const int tempConst;//只能通过初始化列表进行初始化赋值
int temp;
int* tempPtr = new int(3);
const int* tempConstPtr = nullptr;
int* const tempPtrConst = nullptr;
const int* const tempConstPtrConst = nullptr;
};
int main()
{
if(true)
{
Demo demo;
std::cout<<demo.getTempConst()<<std::endl;
std::cout<<demo.getTemp()<<std::endl;
std::cout<<*demo.getTempPtr()<<std::endl;
std::cout<<*demo.getTempConstPtr()<<std::endl;
std::cout<<*demo.getTempPtrConst()<<std::endl;
std::cout<<*demo.getTempConstPtrConst()<<std::endl;
demo.test();//right
}
const Demo demoConst;
demoConst.getTempConst();//Right
demoConst.test();//error
std::cout<<"main end"<<std::endl;
return 0;
}
Demo类定义了以下6个成员变量: 常量tempConst, 变量temp, 普通指针tempPtr, 指向常量的指针tempConstPtr, 常量指针tempPtrConst, 指向常量的常量指针tempConstPtrConst。
构造函数依次对6个成员变量进行赋值,对于const修饰的变量必须使用初始化列表进行初始化赋值,不能再构造函数体内进行赋值。
类中一般获取私有成员变量的值,通过定义get方法进行获取,需要注意的是当获取的是指针类型变量的值时,而我们不希望外部通过get方法获取的指针区修改变量的值,这时候使用const修饰get方法返回值,这样就可以了。
再一个在开发时我们定义类中的某些成员函数时并不希望在内部修改类的成员变量,就可以在成员函数后添加const关键字,只是为了开发时可以让编译器提醒你正在修改成员变量的错误。
const修饰类对象时,此类对象只能调用const修饰的成员函数,就避免了类对象值被修改的问题。
最后还涉及一点内存泄漏的问题,在类内部如果在堆区分配了内存,一定要在析构函数中delete掉。