您的位置:首页 > 其它

条款28 避免返回handles指向对象内部成分

2015-09-09 21:16 260 查看
/*条款28 避免返回handles指向对象内部成分*/
/*handles: 指针,引用,迭代器*/
//设计一个矩形类,为了对象尽可能小,把点放在一个助的struct 内
#include<iostream>
#include<memory>
using namespace std;
class Point{
public:
Point(int x = 0, int y = 0) :m_x(x), m_y(y){}
void setX(int newVal){
m_x = newVal;
}
void setY(int newVal){
m_y = newVal;
}
private:
int m_x;
int m_y;
};
struct RectData{

Point ulhc;
Point lrhc;
};
class Rectangle{
//..
public:
Rectangle(Point c1, Point c2):pData(new RectData){
pData->ulhc = c1;
pData->lrhc = c2;
}
Point&upperLeft()const{//返回值应加const 以配合常属性函数的本意,也增加了封装性
return pData->ulhc;//返回handles类型时注意对象因离开作用域析构导致的空handles
}
Point&lowerRight()const{
return pData->lrhc;
}
private:
shared_ptr<RectData>pData;
};
#include<iostream>
using namespace std;
int main(){
Point coord1(0, 0);
Point coord2(100, 100);
const Rectangle res(coord1, coord2);
res.upperLeft().setX(50);//修改了一个常对象
system("pause");
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: