我是靠谱客的博主 友好茉莉,这篇文章主要介绍C++基础知识 - const成员函数,现在分享给大家,希望可以做个参考。

const成员函数

  • 需求分析:
    const的Human对象,不能调用普通的成员函数。

  • 分析:
    C++认为,const(常量)对象,如果允许去调用普通的成员函数,而这个成员函数内部可能会修改这个对象的数据成员!而这讲导致const对象不再是const对象!

  • 【类比】:专一男就是const对象,撩妹是方法实现,就是普通的成员函数,如果允许专一男调用撩妹,那么专一男,也就不专一了!

  • 解决方案:
    如果一个成员函数内部,不会修改任何数据成员,就把它定义为const成员函数。
    在这里插入图片描述

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
定义: string getName() const; 实现: string Human::getName() const { return name; } 调用: const Human h1; Human h2; h1.getName(); h2.getName();

 
Human.h

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#pragma once #include <string> #include <iostream> #include <Windows.h> using namespace std; class Human { public: Human(); //定义了const成员函数 string getName() const; int getAge(); private: string name; //姓名 int age; //年龄 };

 
Human.cpp

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include "Human.h" Human::Human() { name = "无名"; age = 18; humanCount++; } string Human::getName() const { //cosnt函数内禁止修改任何数据 //age = 10; return name; } int Human::getAge() { return age; }

 
main.cpp

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include "Human.h" using namespace std; int main(void) { const Human h1; Human h2; h1.getName(); h2.getName(); //const对象禁止调用非const函数 //h1.getAge(); h2.getAge(); system("pause"); return 0; }

 
 

const成员函数内,不能修改任何数据成员!

C++的成员函数设置建议:
如果一个对象的成员函数,不会修改任何数据成员,那么就强烈:
把这个成员函数,定义为const成员函数!

最后

以上就是友好茉莉最近收集整理的关于C++基础知识 - const成员函数的全部内容,更多相关C++基础知识内容请搜索靠谱客的其他文章。

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

评论列表共有 0 条评论

立即
投稿
返回
顶部