19.c++-const

 

1.函数名前加const

对于内置类型,如int

int fun()
const int fun()
int const fun()


一个东东.,没区别

对于自定义类型,或指针,如class  A , int *p

const int* fun()
int* const fun()


意思都是返回的int指针是const的,所以

   int a = *fun();//Ok
   int *b = fun();//挂掉


2.函数名后加const

这个直接看MSDN解释就清楚了,

To declare a constant member function, place the const keyword after the closing parenthesis of the argument list.(const在变量列表后面,也就()后) Theconst 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.(内部不能改变数据成员(不是它的变量列表,看清楚哦, 是类的数据成员),不能调非const成员函数);

也就是这样写OK:

class A
{
public:
    int fun(int i)const
    {
        i = 0;
    };
private:
	int m_i;
	int m_j;
};


但这样就不行了:

class A
{
public:
	int fun(int i)const
	{
        m_i = 0;
    };
private:
	int m_i;
	int m_j;
};


 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值