在类中的const基本有三种用法
const int func(); // 返回值是const类型
int func(const int); // 参数为const类型
int func(int )const; // 为const类型的成员函数,只能调用类中const类型的变量;
另外,当类的实例是const类型时,也只能调用类中的const成员函数,且只有类的成员函数才能被修饰为const类型;
//Point.h #include <iostream> using namespace std; class Point{ private: int x,y; public: Point(int a,int b){ x=a;y=b; cout<<"Point constructor is called !\n"; }; ~Point(){ cout<<"Point destructor is called !\n"; } public: const int getX(){ return x; } const int getY(){ return y; } public: void setX(const int a,int b) { x=a;y=b; } public: void printPoint() const{ cout<<"const type\n"; cout<<"x="<<x<<",y="<<y<<endl; } void printPoint(){ cout<<"non const type\n"; cout<<"x="<<x<<",y="<<y<<endl; } };
//main.cpp #include <iostream> #include "Point.h" int main(int argc, const char * argv[]) { // insert code here... Point p(10,20); Point const p1(30,40); p1.printPoint(); p.printPoint(); //std::cout << "Hello, World!\n"; return 0; }
cout:
Point constructor is called !
Point constructor is called !
const type
x=30,y=40
not const type
x=10,y=20
Point destructor is called !
Point destructor is called !
Program ended with exit code: 0
将类中的
void printPoint()
函数删除时则输出:
Point constructor is called !
Point constructor is called !
const type
x=30,y=40
const type
x=10,y=20
Point destructor is called !
Point destructor is called !
Program ended with exit code: 0
所以类中的非 const成员函数也可调用const类型成员函数。
时间: 2024-10-24 09:23:34