Note
- 常量对象上可以执行常量成员函数,是因为常量成员函数确保不会修改任何非静态成员变量的值。
- 编译器如果发现常量成员函数内出现了有可能修改非静态成员变量的语句,就会报错。
- 因此,常置成员函数内部也不允许调用类的其他非常置成员函数(静态成员函数除外)。
- 在您可能犯这类错误时,IDE可能会提示您!
| |
| #include <iostream> |
| using namespace std; |
| class Sample |
| { |
| int a; |
| |
| public: |
| Sample() : a(-1) {} |
| |
| void GetValue() const; |
| |
| void test(); |
| |
| void testConst() const; |
| }; |
| |
| void Sample::GetValue() const |
| { |
| cout << "GetValue() const member function was called!@" << endl; |
| |
| cout << "obj.a=" << a << endl; |
| } |
| |
| |
| void Sample::test() |
| { |
| cout << "test() was called!" << endl; |
| cout << "obj.a=" << a << endl; |
| }; |
| void Sample::testConst() const |
| { |
| |
| cout << "testConst() was called!" << endl; |
| cout << "obj.a=" << a << endl; |
| }; |
| int main() |
| { |
| const Sample obj; |
| obj.GetValue(); |
| |
| obj.testConst(); |
| return 0; |
| } |
| |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
2022-08-15 css_float_浮动的认识和使用