您的位置:首页 > 其它

const在函数中的作用

2012-09-13 23:42 183 查看
1.修饰参数,说明在函数中是不能修改它的值

2.修饰返回值,说明函数的返回值是不能被修改的

3.修饰类成员函数体

实例:

#include<iostream>

#include <assert.h>

using namespace std;

//const输入修饰输入参数

char StringCopy(char *strDestination, const char *strSource)

{

assert((strDestination!=NULL)&&(strSource!=NULL));

char * address=strDestination;

while((*strDestination++ = *strSource++)!='\0')

NULL;

return *address;

}

//修饰返回值

const char *GetString(void)

{

char *szOut="日期输入结束";

return szOut;

}

class DTime

{

public:

DTime(int iYear,int iMonth,int iDay)

{

m_nYear=iYear;

m_nMonth=iMonth;

m_nDay=iDay;

}

int GetYear() const{ return m_nYear;}//修饰函数体

int GetMonth() const{ return m_nMonth;}

int GetDay() const{ return m_nDay;}

public:

int m_nYear;

int m_nMonth;

int m_nDay;

};

int main()

{

char szOutStr[256];

char *szInStr="输入年月日";

StringCopy(szOutStr,szInStr);

cout<<szOutStr<<endl;

int nYear;

int nMonth;

int nDay;

cin>>nYear;

cin>>nMonth;

cin>>nDay;

DTime dt(nYear,nMonth,nDay);

cout<<dt.GetYear()<<"-"<<dt.GetMonth()<<"-"<<dt.GetDay()<<endl;

const char *str=GetString();

cout<<str<<endl;

system("pause");

return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: