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;
    }

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

     

  • 相关阅读:
    Delphi Code Editor 之 几个特性(转)
    如何访问局域网的Access数据库?
    Delphi Live Bindings 初探
    重装Delphi10.2的IDE必要设置
    TClientDataSet数据源设置
    js删除数组里的某个数据
    初识localstorage用法
    Component template should contain exactly one root element. If you are using v-if on multiple elements, use v-else-if to chain them instead.
    css实现文本溢出用...显示
    原生js和jquery
  • 原文地址:https://www.cnblogs.com/xydblog/p/3509868.html
Copyright © 2011-2022 走看看