C++面试常见问题——08const关键字
const
-
类内定义
类型名 函数名(参数列表) const{
//函数体;
}
-
类外定义
-
类内申明
类型名 函数名(参数列表);
-
类外定义
类型名 类名::函数名(参数列表){
//函数体;
}
#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(); } -
浙公网安备 33010602011771号