zoukankan      html  css  js  c++  java
  • 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.   

  • 相关阅读:
    Review Python装饰器
    Python自动化开发三元运算 列表解析 生成器表达式
    Python自动化开发函数02
    Python自动化开发函数03
    Python自动化开发文件
    ELK02ELK收集Linux系统平台应用系统日志
    ELK01Elasticsearch
    html5调用摄像头并拍照
    Docker 安装 PostgreSQL
    《TensorFlow+Keras自然语言处理实战》图书介绍
  • 原文地址:https://www.cnblogs.com/mylinux/p/4728372.html
Copyright © 2011-2022 走看看