C++面试常见问题——08const关键字

const

  1. 类内定义

    类型名 函数名(参数列表) const{

    ​ //函数体;

    }

  2. 类外定义

    1. 类内申明

      类型名 函数名(参数列表);

    2. 类外定义

      类型名 类名::函数名(参数列表){

      ​ //函数体;

      }

    #include<iostream>
    
    using namespace std;
    
    class Point{
        int x;				//类内不指明默认为private
        int y;
    public:
        Point():x(5),y(8){}
        Print() const {	\
    		//x += y;				任何试图修改x的操作都会报错,const函数中无法调用非const函数 
    		cout<<x<<" "<<y<<endl;
    	}
        
    };
    
    int main(){
        Point p;
        p.Print();
    }
    
posted @ 2020-02-23 14:49  MenciusYue  阅读(199)  评论(0)    收藏  举报