在这段代码中,const成员函数的用途是什么?我们如何使用此功能? [英] In this code what is the use of const member function? how can we use this function ?
本文介绍了在这段代码中,const成员函数的用途是什么?我们如何使用此功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在此代码中,const成员函数的用途是什么?我们如何使用它,并且可以声明任何数据成员并对其进行初始化?
In this code what is the use of const member function? how can we use it and is it possible to declare any data member and initialize it?
#include<iostream.h>
#include<conio.h>
class X
{
private:
int a;
public:
void fun()
{
a=10;
cout<<a;
}
void fun1() const
{
//a=10;
}
};
int main()
{
X o;
o.fun();
o.fun1();
getch();
return 0;
}
[edit]已添加代码块-OriginalGriff [/edit]
[edit]Code block added - OriginalGriff[/edit]
推荐答案
直接从 ^ ]:
Direct from MSDN[^]:
Declaring a member function with the const keyword specifies that the function is a "read-only" function that does not modify the object for which it is called. A constant member function cannot modify any non-static data members or call any member functions that aren't constant.
哪一部分没有意义?
那么可以在此常量函数中修改静态数据成员吗?"
阅读上面的短语:
常量成员函数不能修改任何非静态数据成员"
What part of that does not make sense?
"then is it possible to modify the static data members in this constant function?"
Read the phrase above:
"A constant member function cannot modify any non-static data members"
这篇关于在这段代码中,const成员函数的用途是什么?我们如何使用此功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文