当前位置:首页 > 通信资讯 > 正文

在Coordinate类中,有一个Display()成员函数和一个Display() const常成员函数,代码如下

?
1 2 3 4 5 6 7 8 9 class Coordinate{ public: Coordinate(int x,int y); void Display() const; void Display(); private: int m_iX; int m_iY; };
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 #include <iostream> #include "Coordinate.h" using namespace std; Coordinate::Coordinate(int x, int y){ this->m_iX = x; this->m_iY = y; } void Coordinate::Display() const{ cout << "Display() const" << endl; } void Coordinate::Display() { cout << "Display()" << endl; }

Display()成员函数和一个Display() const常成员函数是互为重载的,那么如果我们直接像下面这样调用该方法,会调用的是哪个呢?

?
1 2 3 4 5 6 7 8 9 10 #include <iostream> #include "Coordinate.h" using namespace std; int main(){ Coordinate coor(1, 3); coor.Display(); system("pause"); return 0; }

那么运行下程序来看看结果

浅析成员函数和常成员函数的调用关系(浅析成员函数和常成员函数的调用方法)

程序调用的是没有用const修饰的成员的函数,不是说Display()成员函数和一个Display() const常成员函数是互为重载么,那么我们要如何才能让程序调用const修饰的成员函数呢?

其实很简单,只需要在声明的时候加上const就行。

浅析成员函数和常成员函数的调用关系(浅析成员函数和常成员函数的调用方法)

如果在类中如果只有一个常成员函数的话,声明的时候可以不加上const也是可以调用常成员函数的,

?
1 2 3 4 5 6 7 8 class Coordinate{ public: Coordinate(int x,int y); void Display() const; private: int m_iX; int m_iY; };
?
1 2 3 4 5 6 7 8 9 10 11 #include <iostream> #include "Coordinate.h" using namespace std; Coordinate::Coordinate(int x, int y){ this->m_iX = x; this->m_iY = y; } void Coordinate::Display() const{ cout << "Display() const" << endl; }
?
1 2 3 4 5 6 7 8 9 10 #include <iostream> #include "Coordinate.h" using namespace std; int main(){ Coordinate coor(1, 3); coor.Display(); system("pause"); return 0; }

浅析成员函数和常成员函数的调用关系(浅析成员函数和常成员函数的调用方法)

以上这篇浅析成员函数和常成员函数的调用就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持服务器之家。

如果您对该产品感兴趣,请填写办理(客服微信:xiaoxiongyidong)

为您推荐:

发表评论

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。