C++ 常成员函数以及常指针

来源:互联网 发布:网络每天固定时间掉线 编辑:程序博客网 时间:2024/05/17 23:51

代码:

#include <iostream>using namespace std;class Coordinate{public:    Coordinate(int x, int y)    {        // 设置X,Y的坐标        m_iX=x;        m_iY=y;    }    // 实现常成员函数    void printInfo() const    {        cout<<"("<<m_iX<<","<<m_iY<<")"<<endl;    }public:    int m_iX;    int m_iY;};int main(void){    const Coordinate coor(3, 5);    // 创建常指针p    const Coordinate *p=&coor;    // 创建常引用c    const Coordinate &c=coor;    coor.printInfo();    p->printInfo();    c.printInfo();      return 0;}

这里写图片描述
这里写图片描述
常成员函数中为什么不能改变数据成员的值?
这里写图片描述
这里写图片描述
这里写图片描述
这里写图片描述
这里写图片描述
这里写图片描述
这里写图片描述
这里写图片描述
这里写图片描述
对象的常指针和常引用
这里写图片描述
因为printInfo()是常成员函数,常引用只能调用常成员函数,不能调用普通成员函数。

0 0
原创粉丝点击