本文共 1041 字,大约阅读时间需要 3 分钟。
const CTime mCTime;
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 &”
const 初始化时比较特殊,只能通过初始化列表初始化,不能在构造函数赋值
什么事初始化列表呢,见下面c++代码示例
// 构造函数CTime::CTime() // 初始化 const 变量 :m_constValue(10){ m_nNum ++;}
头文件
public: int getConstValue() const;
const 函数定义
int CTime::getConstValue() const { return m_constValue;}
头文件
#ifndef TIME_H#define TIME_Hclass 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#include "Time.h"using namespace std;int main() { const CTime mCTime; cout < <
转载地址:http://wrcti.baihongyu.com/