C++中的const成员函数和const类对象

做各种C++的测试题的时候,最害怕遇到const,const在C++中的用法非常多,慢慢总结一下。

一、常成员函数(const成员函数)

类中的成员函数声明为const,是告诉编译器本函数不会改变调用它的对象的内容

1)const成员函数的声明与定义

常成员函数的声明格式:<类型说明符> <函数名> <(参数表)> const;

在类体之外定义const成员函数时,也要在函数的参数表后面加上关键字const。

#include "iostream"
using namespace std;
struct Student{
    int id;
    void setId(int newId);
    int getId() const;
};
int Student::getId() const {
    return Student::id;
}
void Student::setId(int newId) {
    Student::id = newId;
}
int main()
{
    Student student01;
    student01.setId(160121);
    int id = student01.getId();
    cout<<id<<endl;
    return 0;
}

2)const成员函数不能修改成员数据
const成员函数不能修改类对象中的成员数据(指针除外)。



3)类的const成员函数可以被非const成员函数重载

参考:http://blog.csdn.net/lihao21/article/details/8634876

4)mutable

C++11中定义了mutable关键字,如果我们定义一个了一个const成员函数,但是在某些场景下,我们还是希望能够修改成员数据,那么我们将数据成员声明为mutable,这样不管const成员函数还是非const成员函数都可以修改该数据成员了。


二、const类对象

非const类对象既可以访问const成员函数也可以访问非const成员函数,const类对象只能访问const成员函数

1)定义与声明

const类对象声明格式:const <类型说明符> <对象名> ;

由于const类对象不能对成员数据进行修改,因此在声明的时候,必须对成员数据通过类构造函数进行初始化。


2)const对象只能访问const成员函数

#include "iostream"
using namespace std;
struct Student{
    int id;
    Student(int id){
        this->id= id;
    };
    void setId(int newId);
    int getId() const;
};
int Student::getId() const {
    return Student::id;
}
void Student::setId(int newId) {
    Student::id = newId;
}
int main()
{
    Student student01(1);
    student01.setId(3);
    cout<<student01.getId()<<endl;

    const Student student02(2);
    //st.setId(4); //err const类对象不能调用非const成员函数
    cout<<student02.getId()<<endl;
    return 0;
}


  • 2
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值