#include <iostream>
#include <string>
using namespace std;
class pt{
public:
pt(int a,int b){this->x=a,this->y=b;}
int getX() const {return this->x;} //此处必须加const(关键),否则A.getX()将无法正常调用
int getY() const {return this->y;} //因否则的话A.getX()中的this默认将指代read_only类型的A,从而导致出错
private:
int x;
int y;
};
class tang{
public:
tang(int a,int b,int c,int d);
void printInfo();
void printInfo() const; //等价于void printInfo(const tang* this);
private: //常成员函数中必须使用常数据成员
const pt A; //这两种写法都对
pt const B;
};
tang::tang(int a,int b,int c,int d):A(a,b),B(c,d){
cout<<"Done"<<endl;
}
void tang::printInfo(){
cout<<"printInfo()"<<endl;
cout<<‘<‘<<A.getX()<<‘,‘<<A.getY()<<‘>‘<<endl;
cout<<‘<‘<<B.getX()<<‘,‘<<B.getY()<<‘>‘<<endl;
}
void tang::printInfo() const{
cout<<"printInfo() const"<<endl;
cout<<‘<‘<<A.getX()<<‘,‘<<A.getY()<<‘>‘<<endl;
cout<<‘<‘<<B.getX()<<‘,‘<<B.getY()<<‘>‘<<endl;
}
int main(){
tang p1(1,2,3,4);
p1.printInfo(); //调用不带const的函数
cout<<‘\n‘;
const tang p2(5,6,7,8);
p2.printInfo(); //调用带const的函数
}
原文地址:https://www.cnblogs.com/dart2100/p/8280572.html