• 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.   

  • 相关阅读:
    5月,专用程序猿的经典大作——APUE
    [Android]Can&#39;t create handler inside thread that has not called Looper.prepare()
    HDU 4433 locker 2012 Asia Tianjin Regional Contest 减少国家DP
    mac 下有些工具 app 推荐
    机器学习倚门回首嗅青梅
    Android复制iPhone日期和时间选择器
    更新代码和工具,组织起来,提供所有博文(C++,2014.09)
    poj3349
    web项目启动,运行方法
    jstat
  • 原文地址:https://www.cnblogs.com/mylinux/p/4728372.html
Copyright © 2020-2023  润新知