問題:
#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
請按任意鍵繼續. . .
*/
class Time
{
public:
void show_time (void) const
{
cout<<"year:"<<year<<endl;
year = 11;//error C3490: 由於正在通過常量對象訪問"year",因此無法對其進行修改
}
private:
int year;
};
class Time
{
public:
Time():year(2015)
{
}
void show_time (void) const
{
cout<<"year:"<<year<<endl;
print(11);//error C2662: "Time::print": 不能將"this"指針從"const Time"轉換為"Time &"
}
void print (int i)
{
cout<<"fun i:"<<i<<endl;
}
private:
int year;
};
class Time
{
…
void show_time (void) const
{
cout<<"year:"<<year<<endl;
}
…
private:
const int year;
};