1. class Point {
  2. public:
  3. Point() {}
  4. Point(int x,int y) : x(x),y(y) {}
  5. void setX(int x) { this->x = x; }
  6. void setY(int y) { this->y = y; }
  7. int getX() const { return x; }
  8. int getY() const { return y; }
  9. private:
  10. int x;
  11. int y;
  12. };
  13. struct RectData {
  14. Point m_leftup;
  15. Point m_rightdown;
  16. RectData(Point a,Point b) {
  17. m_leftup = a;
  18. m_rightdown = b;
  19. }
  20. };

使用struct,为了使Rectangle对象尽可能小,结构体里函数是不占空间的

避免返回引用指向对象内部成分

  1. //给客户提供的正方形类
  2. class Rectangle {
  3. public:
  4. Rectangle(Point a,Point b) : prd(make_shared<RectData>(RectData(a,b))) {}
  5. Point& leftUp() const {
  6. return prd->m_leftup;
  7. }
  8. Point& rightDown() const {
  9. return prd->m_rightdown;
  10. }
  11. private:
  12. shared_ptr<RectData> prd;
  13. };
  1. int main() {
  2. Point cord1(0,0);
  3. Point cord2(100,100);
  4. const Rectangle rc(cord1,cord2);
  5. rc.rightDown().setX(15);
  6. cout << rc.rightDown().getX() << endl;
  7. return 0;
  8. }

image.png
矛盾在于:
1、将leftUp和rightDown声明为const函数,目的不是让调用者修改内部数据;但是函数内部返回引用,调用者可以通过引用修改数据
2、rec不可变,但是也确实修改了数据
结论:
1、当成员函数返回一个引用指向对象内部成分时,该成分访问权限从private升至public
2、logical constness:常成员函数返回一个引用指向对象内部成分,且该成分储存于对象之外(可以理解为引用指向了对象之外),调用者可以修改这个数据。比如operator[]

指针、迭代器同理

解决办法

在返回值处加入const
image.png