博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
34 C++基础-const对象和const成员
阅读量:4147 次
发布时间:2019-05-25

本文共 1041 字,大约阅读时间需要 3 分钟。

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_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/

你可能感兴趣的文章
qt实现点击出现窗口,点击其他任何地方窗口消失
查看>>
QML DropArea拖拉文件事件
查看>>
CORBA links
查看>>
读后感:&gt;
查看>>
ideas about sharing software
查看>>
different aspects for software
查看>>
To do list
查看>>
Study of Source code
查看>>
如何使用BBC英语学习频道
查看>>
浅谈Spring声明式事务管理ThreadLocal和JDKProxy
查看>>
初识xsd
查看>>
java 设计模式-职责型模式
查看>>
构造型模式
查看>>
svn out of date 无法更新到最新版本
查看>>
java杂记
查看>>
RunTime.getRuntime().exec()
查看>>
Oracle 分组排序函数
查看>>
删除weblogic 域
查看>>
VMware Workstation 14中文破解版下载(附密钥)(笔记)
查看>>
日志框架学习
查看>>