const 成员函数
来源:互联网 发布:风云无双装备升级数据 编辑:程序博客网 时间:2024/04/30 09:22
任何不会修改数据成员的函数都应该声明为const 类型。如果在编写const 成员函
数时,不慎修改了数据成员,或者调用了其它非const 成员函数,编译器将指出错误,
这无疑会提高程序的健壮性。
以下程序中,类stack 的成员函数GetCount 仅用于计数,从逻辑上讲GetCount 应
当为const 函数。编译器将指出GetCount 函数中的错误。
class Stack
{
public:
void Push(int elem);
int Pop(void);
int GetCount(void) const; // const 成员函数
private:
int m_num;
int m_data[100];
};
int Stack::GetCount(void) const
{
++ m_num; // 编译错误,企图修改数据成员m_num
Pop(); // 编译错误,企图调用非const 函数
xxx//此处报错为:Member function 'xxx' not viable: 'this' argument has type 'xxx', but function is not marked const
return m_num;}
const 成员函数的声明看起来怪怪的:const 关键字只能放在函数声明的尾部,大
概是因为其它地方都已经被占用了。
- const对象const成员函数
- const成员函数及const
- const成员函数
- const成员函数
- const 成员函数
- c++ const 成员函数
- 关于const成员函数
- const成员函数简介
- const 成员函数
- c++ const成员函数
- c++ const成员函数
- c++ const 成员函数
- c++const成员函数
- const成员函数
- const成员函数
- const成员函数
- c++ const成员函数
- const 成员函数
- HDU 4022 Bombing
- C语言结构体 字节对齐
- Linux下开启/关闭防火墙命令
- Linux内网服务器从Windows通过NTP同步时间
- hdoj1228 A+B
- const 成员函数
- DedeCMS修改模板当鼠标有焦点时图片是呈现黄色块
- 一些收藏,标记一下-20120823
- Java Socket 网络编程常见异常
- gdb
- 带标签的break和continue语句(Java、C++)
- javascript写的代理函数
- FPGA_8_20
- [SGU]104. Little Shop of Flowers