我是靠谱客的博主 有魅力朋友,这篇文章主要介绍34 C++基础-const对象和const成员,现在分享给大家,希望可以做个参考。

1. const 对象

  • const 对象不可再被修改
复制代码
1
const CTime mCTime;
  • const 对象不能调用非const类型的成员函数
复制代码
1
2
3
4
5
6
7
const CTime mCTime; mCTime.getHour(); 1>c:usersfadi.sudocumentsvisual studio 2010projectstesttestmain.cpp(10): error C2662: “CTime::getHour”: 不能将“this”指针从“const CTime”转换为“CTime &

2. const 成员

2.1 const 数据成员

const 初始化时比较特殊,只能通过初始化列表初始化,不能在构造函数赋值

2.2 初始化列表

什么事初始化列表呢,见下面c++代码示例

复制代码
1
2
3
4
5
6
7
8
// 构造函数 CTime::CTime() // 初始化 const 变量 :m_constValue(10) { m_nNum ++; }

2.3 const 成员函数

头文件

复制代码
1
2
3
public: int getConstValue() const;

const 函数定义

复制代码
1
2
3
int CTime::getConstValue() const { return m_constValue; }

3. 完整demo

头文件

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#ifndef TIME_H #define TIME_H class CTime { public: CTime(); // const 函数 int getConstValue() const; private: // const 成员变量 const int m_constValue; }; #endif

对象实现

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include "Time.h" // 构造函数 CTime::CTime() // 初始化列表中进行const 变量初始化,格式如下 :m_constValue(10) { } // // const 函数 int CTime::getConstValue() const { return m_constValue; }

访问const

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream> #include "Time.h" using namespace std; int main() { const CTime mCTime; cout <<mCTime.getConstValue()<<endl; return 0; }

最后

以上就是有魅力朋友最近收集整理的关于34 C++基础-const对象和const成员的全部内容,更多相关34内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(87)

评论列表共有 0 条评论

立即
投稿
返回
顶部