在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;
}
|
相关文章
猜你喜欢
- ASP.NET本地开发时常见的配置错误及解决方法? 2025-06-10
- ASP.NET自助建站系统的数据库备份与恢复操作指南 2025-06-10
- 个人网站服务器域名解析设置指南:从购买到绑定全流程 2025-06-10
- 个人网站搭建:如何挑选具有弹性扩展能力的服务器? 2025-06-10
- 个人服务器网站搭建:如何选择适合自己的建站程序或框架? 2025-06-10
TA的动态
- 2025-07-10 怎样使用阿里云的安全工具进行服务器漏洞扫描和修复?
- 2025-07-10 怎样使用命令行工具优化Linux云服务器的Ping性能?
- 2025-07-10 怎样使用Xshell连接华为云服务器,实现高效远程管理?
- 2025-07-10 怎样利用云服务器D盘搭建稳定、高效的网站托管环境?
- 2025-07-10 怎样使用阿里云的安全组功能来增强服务器防火墙的安全性?
快网idc优惠网
QQ交流群
您的支持,是我们最大的动力!
热门文章
-
Debian 8或Debian 9(64 位)安装 .NET Core
2025-05-29 110 -
详细探讨台湾数据中心的环境特点、基础设施建设、及其对业务运营的影响
2025-05-25 41 -
2025-05-29 80
-
2025-05-25 29
-
2025-05-27 48
热门评论




