const functions 总结
来源:互联网 发布:window 安装ubuntu 编辑:程序博客网 时间:2024/06/11 16:59
1. const 放在函数的后面
const 放在函数后面,只有成员函数声明为const 才有意义,const函数里面才有const this 指针。表示不会改变类的成员(除非该class 为 mutable),另外const函数的中隐含的this 指针也变为const this 指针。
如下 MyClass 中Foo(*this,) const, 可以理解为 Foo(const *this) const
#include <iostream>class MyClass{private: int counter;public: void Foo() { std::cout << "Foo" << std::endl; } void Foo() const { std::cout << "Foo const" << std::endl; }};int main(){ MyClass cc; const MyClass& ccc = cc; cc.Foo(); ccc.Foo();}
如下const 函数不允许修改类的成员变量
void Foo() { counter++; //this works std::cout << "Foo" << std::endl; } void Foo() const { counter++; //this will not compile std::cout << "Foo const" << std::endl; }const 函数可以在非const对象中引用,但是非const函数不可以被const对象引用。
class foobar { ... const char* bar();}
void func1(const foobar& fb1, foobar& fb2) { const char* v1 = fb1.bar(); // won't compile const char* v2 = fb2.bar(); // works}
2.const 放在函数的前面
const 放在函数的前面,表示是返回一个const 指针或者引用。
const T& data() const { return data_; }
Class c;T& t = c.data() // Not allowed.const T& tc = c.data() // OK.
关于不可对const & 类型进行赋值,在《Effective c++》 中有个例子
class TextBlock{public:...const char& operator[] (std::size_t position) const{return text[position];}char& operator(std::size_t position){return text[position];}private:std::string text;};
const TextBlock ctb("Word")TextBlock tb("hello")std::cout << tb[0]; // oktb[0] = 'x'; //okstd::cout<<ctb[0]; //okctb[0] = 'x' ; //error
Refference:
http://www.cprogramming.com/tutorial/const_correctness.html
http://stackoverflow.com/questions/16449889/why-using-the-const-keyword-before-and-after-method-or-function-name
0 0
- const functions 总结
- const member functions and const return values
- const (Constant) Objects and const Member Functions
- Item16 Make const member functions thread safe
- const总结
- const总结
- Const总结
- const总结
- const总结
- const总结
- const总结
- const 总结
- const总结
- const总结
- const 总结
- const总结
- const 总结
- const总结
- TCP协议详解(二)
- MATLAB中常用的排列、组合、阶乘函数
- Qt通过句柄操作外部窗口
- JavaScript整理(1)--基本语法
- C++对象模型——成员初始化列表(第二章)
- const functions 总结
- Huffman tree(赫夫曼树、霍夫曼树、哈夫曼树、最优二叉树)
- 预装win8 centos 双系统 双硬盘 efi 启动
- glOrtho2D函数
- Linux下的虚拟Bridge实现
- UART 通信逻辑协议设计(2)
- Android开发中调用系统设置界面
- nefu998整除问题(高精度除法)
- uva 146