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