C++中的const总结

const修饰成员函数

用const修饰的成员函数时,const修饰this指针指向的内存区域,成员函数体内不可以修改
本类中的任何普通成员变量, 当成员变量类型符前用mutable修饰时例外。

int myFun(void) const //const修饰的是成员函数
2 {}//函数内部不能修改 普通成员变量 mutable修饰时例外
1 class Data
2 {
3 private:
4 int data;
5
6 mutable int num;
7 public:
8 //遍历 成员的函数 不会去修改成员的值
9 //如果函数不会更改成员数据 就让编译器知道 这是一个const函数
10 void myPrintData(void) const
11 {
12 //data =10000;//err const修饰函数 函数不能操作普通成员变量
13 cout<<this>data<<endl;
14 //cout<<data<<endl;
15
16 //mutable修饰的成员变量 可以修改
17 num = 200;
18 }
19
20 Data()
21 {
22 cout<<"无参构造"<<endl;
23 }
24 Data(int data)
25 {
26 this>data =data;
27 cout<<"有参构造"<<endl;
28 }
29 Data(const Data &ob)
30 {
31 this>data = ob.data;
32 cout<<"拷贝构造"<<endl;
33 }
34 ~Data()
35 {
36 cout<<"析构函数"<<endl;
37 }
38 };
39 void test02()
40 {
41 Data ob1(100);
42 ob1.myPrintData();
43 }

常对象 const修饰对象 叫常对象

const int num = 10;//系统不会给num开辟空间 num被放入符号表中 如果后期对&num
这时系统才会给num开辟空间

#include <bits/stdc++.h>
#include <stdio.h>
#include <string.h>
#include <iostream>
using namespace std;

class MyClass
{
private:
    int num;
    mutable int a; 
public:
    MyClass(int x):num(x){}

    MyClass& myClass(char *str) 
    {
        cout << str << "********";
        return *this;
    }

    void setTest() const
    {
        // this->num = 12;
        this->a = 10;
    }

    void printNum() const
    {
        cout << num << endl;
    }
};

void test1()
{
    const MyClass ob1(10);
    ob1.printNum();

}

int main(){
    test1();

    system("pause");
    return 0;
} 

在这里插入图片描述
如果此处不加const修饰的话,编译会报错
const MyClass ob1(10);
ob1.printNum();
常对象 只能调用const修饰的函数 遍历成员数据

补充。。。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

玖玖玖_violet

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值