函数前修饰const与函数名后修饰const

#include<iostream>
#include<cstring>
#include<cstdlib>
#include<cstdio>
#include<algorithm>
using namespace std;

class Base{
private:
    int x;
    char *p;
public:
    Base(void){
        x=0;
        p=(char *)malloc(sizeof(10));
        strcpy(p,"123456");
    }
    void Set_x(int tx){
        x=tx;
    }

    //函数名后面加const表示这个对象指针this所指之物是无法改变的
    int Get_x()const{
        //x++;这样编译报错
        return x;
    }

    //返回值是指针类型,防止指针意外变化,所以用const修饰
    const char* ret_p(){
        return p;
    }
};

int main(){
    Base a=Base();
    printf("%d
",a.Get_x());

    //char* y=a.ret_p(); 这样编译会出错,需要const 修饰的
    const char* y=a.ret_p();
    printf("%s
",y);
}

参考:高质量C++C 编程指南

原文地址:https://www.cnblogs.com/huhuuu/p/3460496.html