概述
const成员函数
-
需求分析:
const的Human对象,不能调用普通的成员函数。 -
分析:
C++认为,const(常量)对象,如果允许去调用普通的成员函数,而这个成员函数内部可能会修改这个对象的数据成员!而这讲导致const对象不再是const对象! -
【类比】:专一男就是const对象,撩妹是方法实现,就是普通的成员函数,如果允许专一男调用撩妹,那么专一男,也就不专一了!
-
解决方案:
如果一个成员函数内部,不会修改任何数据成员,就把它定义为const成员函数。
定义:
string getName() const;
实现:
string Human::getName() const {
return name;
}
调用:
const Human h1;
Human h2;
h1.getName();
h2.getName();
Human.h
#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
#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
#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++基础知识 - const成员函数所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复