34 C++基础-const对象和const成员

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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

法迪

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值