C++, const:

       

问题:

  • const成员函数和普通成员函数可以是同名同参数吗? 可以,这是一种函数的重载。
  • const成员函数可不可以修改对象的成员变量的值? 不可以修改。//error C3490: 由于正在通过常量对象访问"year",因此无法对其进行修改
  • 非const成员函数是否可以访问const对象成员? 不可以访问。 //error C2662: "Time::show_time": 不能将"this"指针从"const Time"转换为"Time &"
  • const成员函数是否能调用非const成员函数?不能。
  • const成员函数能否访问非const成员变量?能。

   

 1. const成员函数和普通成员函数可以是同名同参数的,这是一种函数的重载。

#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

请按任意键继续. . .

*/

   2. const成员函数不可以修改对象的成员变量的值。

class Time

{

public:

void show_time (void) const

{

cout<<"year:"<<year<<endl;

year = 11;//error C3490: 由于正在通过常量对象访问"year",因此无法对其进行修改

}

     

     

private:

int year;

};

   3. 非const成员函数不可以访问const对象成员:

   

 4. Const成员函数不能调用非const成员函数;

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;

};

   

 5. const成员函数能访问非const成员变量。但是不能修改。

class Time

{

void show_time (void) const

{

cout<<"year:"<<year<<endl;

}

   

private:

const int year;

};

   

参考:

  1.   

posted @ 2015-08-13 20:34  oucaijun  阅读(630)  评论(0编辑  收藏  举报
下载TeamViewer完整版 下载TeamViewer