函數聲明後面的const用法

void function() const{}

一般咱們會看到一些函數聲明後面會跟着一個const,這個const是作什麼的呢?ios

看一下下面的例子,就知道了。直接在編譯前,就會提示下面的兩個錯誤函數

// 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; }

 

在類成員函數的聲明和定義中,spa

const的函數不能對其數據成員進行修改操做。code

const的對象,不能引用非const的成員函數。對象

相關文章
相關標籤/搜索