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();  
}

猜你喜欢

转载自www.cnblogs.com/hyq-lst/p/12622402.html