1. const 对象
- const 对象不可再被修改
const CTime mCTime;
- const 对象不能调用非const类型的成员函数
const CTime mCTime;
mCTime.getHour();
1>c:\users\fadi.su\documents\visual studio 2010\projects\test\test\main.cpp(10):
error C2662: “CTime::getHour”: 不能将“this”指针从“const CTime”转换为“CTime &”
2. const 成员
2.1 const 数据成员
const 初始化时比较特殊,只能通过初始化列表初始化,不能在构造函数赋值
2.2 初始化列表
什么事初始化列表呢,见下面c++代码示例
// 构造函数
CTime::CTime()
// 初始化 const 变量
:m_constValue(10)
{
m_nNum ++;
}
2.3 const 成员函数
头文件
public:
int getConstValue() const;
const 函数定义
int CTime::getConstValue() const {
return m_constValue;
}
3. 完整demo
头文件
#ifndef TIME_H
#define TIME_H
class CTime {
public:
CTime();
// const 函数
int getConstValue() const;
private:
// const 成员变量
const int m_constValue;
};
#endif
对象实现
#include "Time.h"
// 构造函数
CTime::CTime()
// 初始化列表中进行const 变量初始化,格式如下
:m_constValue(10)
{
}
// // const 函数
int CTime::getConstValue() const {
return m_constValue;
}
访问const
#include <iostream>
#include "Time.h"
using namespace std;
int main() {
const CTime mCTime;
cout <<mCTime.getConstValue()<<endl;
return 0;
}