zoukankan      html  css  js  c++  java
  • 函数前修饰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 编程指南

  • 相关阅读:
    BZOJ 1088 模拟(扫雷经验…)
    BZOJ 1529
    BZOJ 3224
    BZOJ 1192
    BZOJ 1012
    博客搬家说明
    BZOJ 2423 DP
    BZOJ 1789&1830 推式子 乱搞
    BZOJ 1588
    拆点:虫洞
  • 原文地址:https://www.cnblogs.com/huhuuu/p/3460496.html
Copyright © 2011-2022 走看看