关于const

老码观察 2008-10-26 10:17:57
在一个函数的后面加上const有什么用?
例如:
char sum(int x,int y)const
...全文
215 25 打赏 收藏 转发到动态 举报
写回复
用AI写文章
25 条回复
切换为时间正序
请发表友善的回复…
发表回复
luxiaoxun 2008-10-27
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 jieao111 的回复:]
百度const的用法
[/Quote]

支持
xxzh1 2008-10-27
  • 打赏
  • 举报
回复
常函数,不改变参数的值。
lzp765 2008-10-27
  • 打赏
  • 举报
回复
gg 啊
zhuwanglove 2008-10-27
  • 打赏
  • 举报
回复
学习了
plusbug 2008-10-27
  • 打赏
  • 举报
回复
受益了
gengxiaoyu 2008-10-27
  • 打赏
  • 举报
回复
sum应该是一个成员函数,则调用它的对象不会被修改
cruxsky 2008-10-27
  • 打赏
  • 举报
回复
搜一下
kingofice 2008-10-27
  • 打赏
  • 举报
回复
1楼答案,(1)是错误的,(2)是对的。
(1)const对象的访问只能靠const成员函数
(2)const成员函数不被允许修改它所在对象的任何一个数据成员。

const修饰一个变量,表示该变量是常量。修饰类的成员变量的时候,该变量仅能在构造函数的参数初始化列表中进行一次初始化,此后就仅允许读,而不允许写了。
太乙 2008-10-27
  • 打赏
  • 举报
回复
sum不修改任何数据!
xuxingok 2008-10-27
  • 打赏
  • 举报
回复
mark
shuangbi 2008-10-27
  • 打赏
  • 举报
回复
引用自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.

To declare a constant member function, place the const keyword after the closing parenthesis of the argument list. The const keyword is required in both the declaration and the definition. A constant member function cannot modify any data members or call any member functions that aren't constant.



// constant_member_function.cpp
class Date
{
public:
Date( int mn, int dy, int yr );
int getMonth() const; // A read-only function
void setMonth( int mn ); // A write function; can't be const
private:
int month;
};

int Date::getMonth() const
{
return month; // Doesn't modify anything
}
void Date::setMonth( int mn )
{
month = mn; // Modifies data member
}
int main()
{
Date MyDate( 7, 4, 1998 );
const Date BirthDate( 1, 18, 1953 );
MyDate.setMonth( 4 ); // Okay
BirthDate.getMonth(); // Okay
BirthDate.setMonth( 4 ); // C2662 Error
}


luojc714 2008-10-27
  • 打赏
  • 举报
回复
好像这只能用在类成员函数中吧!表示此函数不会更改除mutable成员外的其它所有成员。
美丽海洋 2008-10-27
  • 打赏
  • 举报
回复
(1)const成员函数不被允许修改它所在对象的任何一个数据成员。
(2)const成员函数能够访问对象的const成员,而其他成员函数不可以。
zsdhust 2008-10-27
  • 打赏
  • 举报
回复
避免无意修改成员数据。
visame 2008-10-26
  • 打赏
  • 举报
回复
首先你要明白, char sum(int x,int y)const这个只能出现在类中。
zhangyq73 2008-10-26
  • 打赏
  • 举报
回复
常方法
beingstudio 2008-10-26
  • 打赏
  • 举报
回复
(1)const对象的访问只能靠const成员函数
(2)const成员函数不被允许修改它所在对象的任何一个数据成员。

如下面代码
错误是 const对象的访问只能靠const成员函数


class X
{
public:
int f_1() const
{
return m_i + 10;
}

int f_2()
{
return m_i++;
}

private:
int m_i;
};



int _tmain(int argc, _TCHAR* argv[])
{
X a;
const X b;

a.f_1();
a.f_2();

b.f_1();
b.f_2();

return 0;
}
insuya 2008-10-26
  • 打赏
  • 举报
回复
yes!!
chlaws 2008-10-26
  • 打赏
  • 举报
回复
很完整了
jqx_ah 2008-10-26
  • 打赏
  • 举报
回复
LZ google一下吧~~ 网上就是一个大的图书馆
加载更多回复(5)

65,211

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧