zoukankan      html  css  js  c++  java
  • 函数声明后面的const用法

    void function() const{}

    通常我们会看到一些函数声明后面会跟着一个const,这个const是做什么的呢?

    看一下下面的例子,就知道了。直接在编译前,就会提示下面的两个错误

    // test1107.cpp : 定义控制台应用程序的入口点。
    //
    
    #include "stdafx.h"
    #include <iostream>
    using namespace std;
    
    class aa{
        int num;
    public:
        aa(){
            int b =10;
            num = b;
        };
        void out1(){
            cout<<num<<endl;
        }
        void out2() const{
            cout<<num<<endl;
        }
        void out3() const{
            num+=10; //出错,const函数不能修改其数据成员
            cout<<num<<endl;
        }
    
    };
    int _tmain(int argc, _TCHAR* argv[])
    {
        aa a1;
        a1.out1();
        a1.out2();
        a1.out3();
        const aa a2;
        a2.out1(); // 错误,const的成员 不能访问非const的函数
        a2.out2();
        a2.out3();
        return 0;
    }

    在类成员函数的声明和定义中,

    const的函数不能对其数据成员进行修改操作。

    const的对象,不能引用非const的成员函数。

  • 相关阅读:
    poj 3422 Kaka's Matrix Travels
    poj 1815 Friendship
    poj 1966 Cable TV Network
    黑暗
    【bzoj2741】[FOTILE模拟赛] L
    整数拆分
    LCIS
    原题的旅行
    【codeforces gym】Increasing Costs
    【noip模拟】D(==)
  • 原文地址:https://www.cnblogs.com/xing901022/p/3413019.html
Copyright © 2011-2022 走看看