123456

 

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在变量列表后面,也就()后) 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.(内部不能改变数据成员(不是它的变量列表,看清楚哦, 是类的数据成员),不能调非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;
};


 

posted on 2011-12-01 17:07  hgy413  阅读(137)  评论(0编辑  收藏  举报

导航