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;
}
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;
}
相关文章推荐
- 【ThinkingInC++】40、论const对函数返回值的作用
- 非静态成员函数后面的const作用
- C++在函数声明时,后面跟个const的作用
- C++关于类成员函数在参数列表后加const的作用,以及使用条件
- 成员函数后面加上const的作用
- 成员函数 加 const 的作用
- 类成员函数中的const不同位置的作用
- 函数后面的const的作用
- 函数后面加一个const的作用
- c++ 函数后面 const 作用
- 函数名后面加上const的作用
- const在函数和方法上的防修改作用
- const作为函数返回值的作用
- 成员函数后面加上const的作用
- const、&在定义函数返回的作用及接收返回变量的类型
- C语言学习9: malloc动态内存存储,动态内存分配去空格字符增长版,动态内存分配去符号incr增长版,型参和返回值都是int型的函数的指针,main函数的地址也可以用指针指向,typedef定义函数指针,函数定义与嵌套的作用,返回函数指针类型,const作用
- C++成员函数末尾const关键字的作用
- Const 修饰成员函数的作用
- const在函数中间的作用
- 解释此函数原型中三个const的作用const int* computeResult( const int& var ) const。