C++ const总结

const是代码中的常客。Today,我就略加总结。

        主要通过几段代码讲解,

Code sec1:

#include<stdio.h>
int funa(const int& a)
{
printf("%d\n",a);
}
int funb(int& a)
{
printf("%d\n",a);
}
int func(int a)
{
printf("%d\n",a);
}
int fund(const int a)
{
printf("%d\n",a);
}
int main()
{
int m=3;
const int n=4;
funa(m);
funa(n);
funa(5);
funb(m);
funb(n);
funb(5);
func(m);
func(n);
func(5);
fund(m);
fund(n);
fund(5);
}
ok,代码首先定义了4个函数,funa,funb,func,fund,形参分为引用和非引用两类,且一次搭配const进行测试。

结论:只有进行引用传递时,const生效,const类型实参不能传给非const类型形参,反之可以。基本类型常量属于const类型。

Code sec2:

#include<stdio.h>
#include<cstring>
using namespace std;
int funa(const char* a)
{
printf("%s\n",a);
}
int funb(char* a)
{
printf("%s\n",a);
}
int main()
{
char *p=new char[4];
strcpy(p,"atm");
funa(p);
funa("atm");
funb(p);
funb("atm");
}
ok,代码首先定义了两个函数funa和funb,形参分别为const char*和char*。

结论:指针传递时,const生效,结论同上。

Code sec3:

#include<stdio.h>
class Stu
{
public:
Stu(){};
void say() const;
};
void Stu::say() const
{
printf("i am tom\n");
}
int main()
{
Stu stu;
stu.say();
}

ok,代码定义了一个简单的stu类。

结论:const放在成员函数声明后,表示函数不会改变对象。

Code sec4:

#include<stdio.h>
#include<cstring>
#include<iostream>
class TestStr
{
public:
char *str;
TestStr();
~TestStr();
char &operator[](int i);
const char &operator[](int i) const;
friend ostream &operator<<(ostream &os,const TestStr &st);
};
TestStr::TestStr()
{
str=new char[4];
using std::strcpy;
strcpy(str,"c++");
}
TestStr::~TestStr()
{
delete[] str;
}
char &TestStr::operator[](int i)
{
cout<<"! const invoked"<<endl;
return str[i];
}
ostream &operator<<(ostream &os,const TestStr &st)
{
return os<<st.str<<endl;
}
const char &TestStr::operator[](int i) const
{
cout<<"const invoked"<<endl;
return str[i];
}
int main()
{
TestStr tsr;
cout<<tsr;
cout<<tsr[0]<<endl;
tsr[0]='b';
cout<<tsr;
const TestStr ctsr;
cout<<ctsr;
cout<<ctsr[0]<<endl;
//ctsr[1]='d';
cout<<ctsr;
}
ok,代码定义了一个简单的TestStr类,成员函数包括构造函数、析构函数并且重写了‘《’和‘[]’运算符。
结论:下面是结果,你可能已经看到了, const对象使用下标时调用const方法,而非const对象,则调用非const方法。
c++
! const invoked
c
! const invoked
b++
c++
const invoked
c
c++

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值