c++ colon const
来源:互联网 发布:linux 解压zip 覆盖 编辑:程序博客网 时间:2024/06/01 07:49
As others have said, it's an initialisation list. You can use it for two things:
- Calling base class constructors
- Initialising member variables before the body of the constructor executes.
For case #1, I assume you understand inheritance (if that's not the case, let me know in the comments). So you are simply calling the constructor of your base class.
For case #2, the question may be asked: "Why not just initialise it in the body of the constructor?" The importance of the initialisation lists is particularly evident for const
members. For instance, take a look at this situation, where I want to initialise m_val
based on the constructor parameter:
class Demo{ Demo(int& val) { m_val = val; }private: const int& m_val;};
By the C++ specification, this is illegal. We cannot change the value of a const
variable in the constructor, because it is marked as const. So you can use the initialisation list:
class Demo{ Demo(int& val) : m_val(val) { }private: const int& m_val;};
That is the only time that you can change a const member variable. And as Michael noted in the comments section, it is also the only way to initialise a reference that is a class member.
Outside of using it to initialise const
member variables, it seems to have been generally accepted as "the way" of initialising variables, so it's clear to other programmers reading your code.
-------------------------------------------------------------
When you add the const
keyword to a method the this
pointer will become const, and you can therefore not change any member code. (Unless you use mutable
, more on that later).
The const
keyword is part of the functions signature which means that you can implement two similar methods, one which is called when the object is const, and one that isn't.
#include <iostream>class MyClass{private: int counter = 0;public: void Foo() { std::cout << "Foo" << std::endl; } void Foo() const { std::cout << "Foo const" << std::endl; }};int main(void){ MyClass* cc = new MyClass(); const MyClass* ccc = cc; cc->Foo(); ccc->Foo(); delete cc; ccc = null; return 0;}
This will output
FooFoo const
- c++ colon const
- const c
- const【C++】
- const ||c
- C++Const
- [c++]const
- C++:const
- const用法(C/C++)
- C++/C const问题
- 【c/c++】const引用
- When Colon Scripting is comming
- readonly vs. const [C#]
- C++(二)const
- C语言const介绍
- C语言const介绍
- readonly vs. const [C#]
- readonly vs. const [C#]
- c++:const 操作小结
- 机器翻译中的参数调整---MERT方法
- UVa 514 - Rails 注意最后的输出
- 将Win7任务栏中的库修改为计算机
- 请求参数没有效果:errbuf,retcode放置位置导致异常
- POJ 2418 Hardwood Species
- c++ colon const
- The Hare and The Tortoise
- 嵌入式linux下使用busybox的crond服务的方法+问题及解决
- Dialog更换鼠标图片
- c 问题记录说明
- XHTML CSS 常见问题和解决方案
- Cannot find class [org.hibernate.ejb.HibernatePersistence
- 配置虚拟主机
- android adb 命令进入fastboot 两种方法