??? ??
Problem:
- Can the const member function and the ordinary member function be the same with the same parameter? Yes, this is an overload of a function.
- Can the const member function modify the value of a member variable of an object? Cannot be modified. Error C3490: cannot be modified because "year" is being accessed through a const object
- Does the non-const member function have access to const object members? cannot be accessed. Error C2662: "Time::show_time": Cannot convert "This" pointer from "Const time" to "Time &"
- Can the const member function invoke a non-const member function? No.
- Can the const member function access non-const member variables? Yes.
??
? 1.? The const member function and the ordinary member function can be the same with the same parameter, which is an overload of a function.
#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;
}
? ??
/*
year:2015
year:2015
Please press any key to continue ...
*/
??? 2.? The const member function cannot modify the value of a member variable of an object.
Class time
{
Public
void Show_time (void) const
{
cout<< "Year:" <<year<<endl;
Year = 11;//error C3490: cannot be modified because "year" is being accessed through a const object
}
? ??
? ??
Private
int year;
};
??? 3.? Non-const member functions do not have access to const object Members:
??
? 4.? A const member function cannot call a non-const member function;
Class time
{
Public
???? Time (): Year (2015)
???? {
???????? ?
????}
??
???? void Show_time (void) const
???? {
???????? cout<< "Year:" <<year<<endl;
???????? print (one);//error C2662: "time::p rint": "This" cannot be The pointer is converted from "constTime" 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 cannot be modified.
Class time
{
...
void Show_time (void) const
{
cout<< "Year:" <<year<<endl;
}
...
??
Private
const int year;
};
??
Reference:
- constant object and constant member function ? http://blog.chinaunix.net/uid-21411227-id-1826906.html
??
C + +, const: