transferred from: http://www.cnblogs.com/this-543273659/archive/2011/07/18/2109922.htmlfirst, the regular member function detailed
Declares the:< type identifier > function name (parameter table)const;
Description
(1) The const is part of the function type, and the keyword is also taken in the implementation section.
(2) The Const keyword can be used to differentiate between overloaded functions.
(3) A constant member function cannot update a member variable of a class, nor can it call a member function that is not const-decorated in the class, but can only invoke a constant member function.
A, using an example to understand that a const is part of a function type, the implementation part also takes the keyword.
Class a{
Private
int w,h;
Public
int GetValue () const;
int GetValue ();
A (int x,int y)
{
W=x,h=y;
}
A () {}
};
the int a::getvalue () const// Implementation section also takes this keyword
{
return w*h;//????
}
void Main ()
{
A const a (3,4);
A c (2,6);
Cout<<a.getvalue () <<c.getvalue () << "Cctwltest";
System ("pause");
}
B. Use examples to understand overloads of the Const keyword
Class a{
Private
int w,h;
Public
int GetValue () const
{
return w*h;
}
int GetValue () {
return w+h;
}
A (int x,int y)
{
W=x,h=y;
}
A () {}
};
void Main ()
{
A const a (3,4);
A c (2,6);
Cout<<a.getvalue () <<c.getvalue () << "Cctwltest"; output 8 and
System ("pause");
}
C, through an example to understand the constant member function can not update any data members
Class a{
Private
int w,h;
Public
int GetValue () const;
int GetValue ();
A (int x,int y)
{
W=x,h=y;
}
A () {}
};
int A::getvalue () const
{
w=10,h=10;// Error because the constant member function cannot update any data members
return w*h;
}
int A::getvalue ()
{
w=10,h=10;// can update data members
return w+h;
}
void Main ()
{
A const a (3,4);
A c (2,6);
Cout<<a.getvalue () <<endl<<c.getvalue () << "Cctwltest";
System ("pause");
}
D, through examples to understand
1, the constant member function can be called by other member functions.
2, but other very member functions cannot be called.
3, you can call other regular member functions.
Class a{
Private
int w,h;
Public
int GetValue () const
{
return w*h + getValue2 ();// error cannot call other very member functions.
}
int GetValue2 ()
{
return W+h+getvalue ();// correct call to the constant member function
}
A (int x,int y)
{
W=x,h=y;
}
A () {}
};
void Main ()
{
A const a (3,4);
A c (2,6);
Cout<<a.getvalue () <<endl<<c.getvalue2 () << "Cctwltest";
System ("pause");
}
C + + constant member function-const keyword