函數聲明后面的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的成員函數。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM