C++ const常成员函数

C++ const常成员函数

使用const关键字修饰的函数为常成员函数,常见声明如下:
类型说明符 函数名(参数表) const;

注意

const关键字可以用于对重载函数的区分。例如在类中这样声明:
void print();
void print() const;
这是对print的有效重载。
如果仅以const关键字为区分对成员函数的重载,那么通过非const的对象调用该函数,两个重载的函数都可以与之匹配,这时编译器将选择最近的重载函数——不带const关键字的函数。

举例程序如下

#include <iostream>
using namespace std;

class R
{
public:
 //构造函数
 R(int r1,int r2):r1(r1),r2(r2){}
 void print();
 void print() const;//常成员函数
private:
 int r1,r2;
};

void R::print() 
{
 cout<<r1<<":"<<r2<<endl;
}

void R::print() const
{
 cout<<r1<<";"<<r2<<endl;
}

int main()
{
 R a(5,4);
 a.print();
 const R b(20,52);
 b.print();
 return 0;
}

在这里插入图片描述

发布了10 篇原创文章 · 获赞 10 · 访问量 528

猜你喜欢

转载自blog.csdn.net/weixin_46066007/article/details/103762887