zoukankan      html  css  js  c++  java
  • 常量成员函数与常量对象

    一、非常量对象可以访问类的普通成员函数和常量成员函数

    #include <iostream>
    using namespace std;
    
    class Stack
    {
    private:
        int m_num;
        int m_data[20];
    public:
        Stack()
        {
            m_num = 0;
        }
        void Push(int nElem)
        {
    
        }
        int Pop()
        {
            GetCount();
            return 0;
        }
        int GetCount()const                //常量成员函数
        {
        
            return 0;
        }
        
    };
    
    int main()
    {
        Stack stack;            
        
        stack.GetCount();                //非常量对象可以调用常量成员函数
        stack.Pop();                     //非常量对象可以调用非常量成员函数
    
        return 0;
    }

    二、常量对象只能访问常量成员函数,不能访问普通成员函数

    #include <iostream>
    using namespace std;
    
    class Stack
    {
    private:
        int m_num;
        int m_data[20];
    public:
        Stack()
        {
            m_num = 0;
        }
        void Push(int nElem)
        {
    
        }
        int Pop()
        {
            GetCount();
            return 0;
        }
        int GetCount()const                //常量成员函数
        {
        
            return 0;
        }
        
    };
    
    int main()
    {
        const Stack cStack;
        
        cStack.GetCount();                //调用常量对象的常量成员函数
        cStack.Pop();                     //调用该函数出错,常量对象不能调用非常量成员函数
        return 0;
    }

    三、常量成员函数不能调用普通成员函数,也不能修改数据成员的值;普通成员函数可以调用常量成员函数

    #include <iostream>
    using namespace std;
    
    class Stack
    {
    private:
        int m_num;
        int m_data[20];
    public:
        Stack()
        {
            m_num = 0;
        }
        void Push(int nElem)
        {
    
        }
        int Pop()
        {
            GetCount();                    //正确,普通成员函数可以调用常量成员函数
    
            return 0;
        }
        int GetCount()const            
        {
            m_num++;                     //出错,常量成员函数不能修改数据成员
    
            Pop();                        //出错,常量成员函数不能调用普通成员函数
    
            return 0;
        }
        
    };
    
    int main()
    {
        Stack stack;            
    
        stack.GetCount();            
        stack.Pop();                    
        return 0;
    }

    可以用下面这张图来表示“常量对象, 普通对象, 常量成员函数, 普通成员函数” 的关系。

     

  • 相关阅读:
    最难的事
    性格决定命运,习惯决定未来
    系统构架师之路
    时间是经不起浪费的
    如何投资自己,增加自身价值!
    最好的程序员大多是自学成才的
    杂记
    Win7启动Oracle出错
    推荐代码生成器工具排行
    Hibernate 与 Oracle 11g 的问题
  • 原文地址:https://www.cnblogs.com/xydblog/p/3509868.html
Copyright © 2011-2022 走看看