C++-使用const對函數定義


使用const進行函數的定義

/*
使用const進行定義
*/ 
#include <iostream>

using namespace std; 

class A{
public:
    A(int i = 0):m_data(i) {} 
    void print(void) const { //const表示類不能進行變化
        // ++m_data; 
        cout << m_data << endl; 
    }

private:
    int m_data; 
}; 

const 只讀模式,外部的函數對類型不進行改變

/* 
ConstFunc使用實例 
*/ 
#include <iostream>

using namespace std; 

class A{
public:
    void func1(void) const {
        cout << "常函數" << endl; 
        // func2(); //錯誤 因為func1是const類型的
    }
    void func2(void) {
        cout << "非常函數" << endl; 
        m_i++; 
        func1(); 
    }
private:
    int m_i; 
}; 

int main() {
    A a; 
    a.func1(); 
    a.func2(); 
    const A a1 = a; //只讀類型,外部不能改變其類型 
    // a1.m_i++; 
    a.func1(); 
    a.func2(); 
    const A* pa = &a; 
    pa->func1(); 
    
    const A& ra = a; 
    ra.func1(); 
    
}

const 根據函數的匹配度進行匹配

/*
構造const函數
*/ 
#include <iostream>

using namespace std; 

class A{
public:
    void func(int a = 0) const{
        cout << "常函數" << endl;         
    }
    void func(int a = 0){
        cout << "非常函數" << endl; 
    } 
private:
    int m_a; 
}; 

int main() {
    A a; 
    a.func(); 
    const A a1 = a; //const 匹配后面一個函數 
    a1.func();  
}

 


免責聲明!

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



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