const用途
首先,说下最基本的const用途:
case1:const修饰变量,表示是常量,程序中不能更改,存放在常量存储区。
例如:
const int a = 100;
case2:const修饰函数形参,表示传入的参数在函数内部不能修改。
例如:
class Test
{
public:
Test(const Test& obj) //自定义的拷贝构造函数
{
// obj在该函数内部不能更改
}
};
case3:非静态成员函数后置const,表示成员函数隐含传入的this指针是const指针。那么在该成员函数里,任何修改它所在类的成员的操作都是不允许的!
注意:后置const只能加在非静态成员函数后,加到*非成员函数或者静态成员*后面都是错误的。
例如:
class Test
{
public:
int m_num;
int getNum() const
{
m_num = 1; //error,不能在后置const函数里修改成员变量
}
bool operator == (const Test& obj) const
{
}
}
易错点
先看个例子
// test.cpp
#include <iostream>
#include <list>
using namespace std;
class Test
{
public:
int m_num;
Test()
{
cout << "call constructor function..no param.." << endl;
}
Test(int num)
{
cout << "call constructor function..1 param.." << endl;
m_num = num;
}
Test(const Test& obj)
{
cout << "call copy constructor function.." << endl;
}
~Test()
{
cout << "call destructor function.." << endl;
}
bool operator == (const Test& obj)
{
return false;
}
};
int main()
{
Test a(1);
Test b(2);
if (a==b)
;
return 0;
}
// compile cmd
// g++ -g test.cpp -o test
这个编译不会有错,即便==的重载函数没有加后置const,编译也没有错。
但是再看下面一个例子
// test.cpp
#include <iostream>
#include <list>
using namespace std;
class Test
{
public:
int m_num;
Test()
{
cout << "call constructor function..no param.." << endl;
}
Test(int num)
{
cout << "call constructor function..1 param.." << endl;
m_num = num;
}
Test(const Test& obj)
{
cout << "call copy constructor function.." << endl;
}
~Test()
{
cout << "call destructor function.." << endl;
}
bool operator == (const Test& obj)
{
return false;
}
};
int main()
{
Test a(1);
Test b(2);
list<Test> list1;
list1.push_back(a);
list1.push_back(b);
list <Test> list2;
list2.push_back(a);
list2.push_back(b);
if (list1 == list2)
;
return 0;
}
// compile cmd
// g++ -g test.cpp -o test
这个编译就出错了,如下:
当使用了std里的一些模板类,比如(list、set、vector等等),如果没有严格加后置const,那么编译就会出错,因为list的==重载函数要求都是const类型,而Test类的==重载函数不指定后置const的话,无法确定在Test的==重载函数会不会修改Test的成员。
编码好习惯
1、如果一个非静态成员函数不会修改该类的成员变量,都强制加一下后置const。
2、如果传入函数的参数在函数内部不会修改的话,函数参数也应该加上const修饰。