C ++, const:, const
Problem:
- Can a const member function and a common member function have the same parameter name? Yes. This is a function overload.
- Can a const member function modify the value of a member variable of an object? It cannot be modified. // Error C3490: Unable to modify because the constant object is accessing "year"
- Can non-const member functions access const object members? Not accessible. // Error C2662: "Time: show_time": the "this" pointer cannot be converted from "const Time" to "Time &"
- Can a const member function call a non-const member function? No.
- Can the const member function access non-const member variables? Yes.
1. const member functions and common member functions can be the same parameters with the same name, which is a function overload.
# Include "stdafx. h"
# Include <iostream>
Using namespace std;
Class Time
{
Public:
Time (): year (2015)
{
}
Void show_time (void) const
{
Cout <"year:" <year <endl;
}
Void print (int I)
{
Cout <"fun I:" <I <endl;
}
Void print (int I) const
{
Cout <"const fun I:" <I <endl;
}
Private:
Const int year;
};
Int _ tmain (int argc, _ TCHAR * argv [])
{
Time time;
Time. show_time ();
Time. print (1 );
Time const ctime;
Ctime. show_time ();
Ctime. print (1 );
System ("pause ");
Return 0;
}
/*
Annual: 2015
Annual: 2015
Press any key to continue...
*/
2. the const member function cannot modify the value of the member variable of the object.
Class Time
{
Public:
Void show_time (void) const
{
Cout <"year:" <year <endl;
Year = 11; // error C3490: Unable to modify because the constant object is accessing "year"
}
Private:
Int year;
};
3. Non-const member functions cannot access const object members:
4. Const member functions cannot call non-const member functions;
Class Time
{
Public:
Time (): year (2015)
{
}
Void show_time (void) const
{
Cout <"year:" <year <endl;
Print (11); // error C2662: "Time: print": the "this" pointer cannot be converted from "const Time" to "Time &"
}
Void print (int I)
{
Cout <"fun I:" <I <endl;
}
Private:
Int year;
};
5. the const member function can access non-const member variables. But it cannot be modified.
Class Time
{
...
Void show_time (void) const
{
Cout <"year:" <year <endl;
}
...
Private:
Const int year;
};
Refer: