一.const修饰成员变量
1.const修饰类数据成员必须要初始化
#include <iostream>
using namespace std;
class A
{
public: A() { cout << "const x = " << x << endl; } private: const int x; }; int main() { A a; return 0; }
上面代码没有对成员变量进行初始化,编译的时候会报如下错误
/home/zzz/Workspace/test/cplusplus/const.cpp: In constructor ‘A::A()’:
/home/zzz/Workspace/test/cplusplus/const.cpp:6:4: error: uninitialized const member in ‘const int’ [-fpermissive] A() ^ /home/zzz/Workspace/test/cplusplus/const.cpp:11:14: note: ‘const int A::x’ should be initialized const int x;
const成员初始化第一种在类内
#include <iostream>
using namespace std;
class A
{
public: A() { cout << "const x = " << x << endl; } private: const int x = 100; }; int main() { A a; return 0; }
const成员初始化第二种在初始化列表
#include <iostream>
using namespace std;
class A
{
public: A():x(100) { cout << "const x = " << x << endl; } private: const int x; }; int main() { A a; return 0; }
2.const修饰的数据成员可以在非const函数中使用,但不可以修改
二.const修饰成员函数
(const可以修饰类成员函数不可以修饰全局函数)
const修饰函数以后承诺不改变,在本函数中不会发生,改变数据成员的行为
只能调用const成员函数
void foo()const
{
}
const修饰函数可以构成重载
const构成的重载函数,非const对象,优先调用非const版本
const对象只能调用const版本
void foo()
{
}
void foo()const
{
}
void foo(int& a, int& b)
{
}
void foo(const int& a, const int& b)
{
}
三.const修饰对象
const修饰对象,其内可以有非const数据成员,但不可修改。只能调用const成员函数