C++const 修饰类的用法

    xiaoxiao2026-04-11  7

    C++  const 修饰类用法   

    1.修饰数据成员 

    初始化位置只能在参数列表里面 

    被const修饰的数据成员不能被修改  

    2.修饰成员函数   位置 函数申明之后,实现体之前   意义: const承诺不会修改数据成员             能访问const和非const数据成员   但不能修改 非const数据成员             只能访问const成员函数  构成重载   const对象只能调用const成员函数。 非const成员对象,优先调用非const成员函数,若无则可调用const成员函数    3.修饰类对象   const 修饰函数,是从函数层面,不修改数据    const修饰对象,是从对象层面,不修改数据,只能调用const成员函数 #include <iostream> using namespace std; class A { public: A(int v) :val(v) {} void dis() const { cout << val << endl; // x = 200; 不可以 /***********/ int a; a = 100; //可以 /***********/ // print(); 也不可以 } void print() { x = 100; } /******构成重载*******/ void play() { cout << "void play()" << endl; } void play()const { cout << "void play() const" << endl; } void plays()const { cout << "void play() const" << endl; } private: const int val ; // 新版可以这样初始化 const int val = 10; int x, y; }; int main() { //const int i; 必须初始化 A a(5); a.dis(); a.play(); a.plays(); //非const成员对象,优先调用非const成员函数,若无则可调用const成员函数 const A b(5); b.play(); //const对象只能调用const成员函数 system("pause"); return 0; }

    转载请注明原文地址: https://ju.6miu.com/read-1308724.html
    最新回复(0)