zoukankan      html  css  js  c++  java
  • 关于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;
    }
  • 相关阅读:
    ssh端口转发
    linux git命令安装
    linux git命令
    linux cpio命令
    linux 抓包工具
    js 深拷贝 ,浅拷贝
    vue $router 打开新窗口
    excel常用操作
    Kafka Topic的增删改查操作
    linux上删除文件名乱码的文件
  • 原文地址:https://www.cnblogs.com/qq702368956/p/4909633.html
Copyright © 2011-2022 走看看