• 关于C++的const对象


    对于const类对象,类指针, 类引用, 只能调用类的const成员函数.

    1.const成员函数不允许被修改它所在对象的任何一个成员变量.

    2.const成员函数能访问对象的const成员, 而其他成员函数不可以.

    #include <iostream>
    using namespace std;
    
    class CTest
    {
    private:
        int m_iX;
        int m_iY;
    public:
        CTest(int x = 0, int y = 0)
        {
            m_iX = x;
            m_iY= y;
        }
        ~CTest()
        {
            m_iY = 9;
        }
        void SetX(int x)
        {
            m_iX = x;
        }
        void SetY(int y)
        {
            m_iY = y;
        }
        void print() const    //只有const成员函数可以访问const对象的const数据成员.
        {
            cout<<"m_iX = "<<m_iX<<endl;
            cout <<"m_iY = "<<m_iY<<endl<<endl;
        }
    };
    
    int main()
    {
        CTest t1(11, 22);
        cout<<"t1打印: "<<endl;
        t1.print();
    
        t1.SetX(33);
        t1.SetY(44);
        cout<<"t1修好值后打印:"<<endl;
        t1.print();
    
        const CTest t2(55, 66);    //const对象的任何成员都不能被修改
        const CTest *p = new CTest(3, 4);
    
        cout<<"打印t2:"<<endl;
        t2.print();
    
    //    t2.SetX(77);        //const对象不能调用非const函数.
    //    t2.SetY(88);
        cout<<"打印指针对象:"<<endl;
        p->print();
    
        t2.~CTest();
        cout<<"t2调用析构函数后:"<<endl;
        t2.print();
    
    
        return 0;
    }
  • 相关阅读:
    设计数据库步骤
    sql练习题
    多表连接查询
    数据约束
    管理并行SQL执行的进程
    关于Oracle数据库后台进程
    配置数据库驻留连接池
    为共享服务器配置Oracle数据库
    关于数据库驻留连接池
    关于专用和共享服务器进程
  • 原文地址:https://www.cnblogs.com/qq702368956/p/4909633.html
Copyright © 2020-2023  润新知