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

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

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

 常量成员函数与常量对象

 

 

 

相关文章:

  • 2021-04-24
  • 2021-08-15
  • 2022-01-20
  • 2022-12-23
  • 2021-09-10
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-07-23
  • 2021-10-08
  • 2022-01-17
  • 2022-02-13
  • 2021-11-21
  • 2022-12-23
相关资源
相似解决方案