这是关于编程风格的一般问题。假设我有一个对象Line,它具有一些方法以及私有(private)变量Point point_a_Point point_b_。假设在某些时候我需要更改两点的位置。在以下情况下,您希望使用哪种编程风格?它们都做相同的事情(或者应该做:我没有编译,但是看起来很简单)。

案例1

Class Line {
public:
  Line(Point point_a, Point point_b) : point_a_(point_a), point_b_(point_b) {}

  void UpdatePoints(Point point_a, Point point_b) {
    point_a_ = point_a; point_b_ = point_b;
  }

  double Distance();

private:
  Point point_a_;
  Point point_b_;
};

int main (int argc, char * const argv[]) {
  Point point_a(0,0,0);
  Point point_b(1,1,1);
  Line line(point_a,point_b);
  std::cout<<line.Distance()<<"\n";

  point_a.x = 1;
  line.UpdatePoints(point_a,point_b);
  std::cout<<line.Distance()<<"\n";
}

案例2
Class Line {
public:
  Line(Point point_a, Point point_b) : point_a_(point_a), point_b_(point_b) {}
  Point& point_a() { return point_a_; }
  Point& point_b() { return point_b_; }
  double Distance();

private:
  Point point_a_;
  Point point_b_;
};

int main (int argc, char * const argv[]) {
  Point point_a(0,0,0);
  Point point_b(1,1,1);
  Line line(point_a,point_b);
  std::cout<<line.Distance()<<"\n";

  line.point_a().x = 1;
  std::cout<<line.Distance()<<"\n";
}

案例3
Class Line {
public:
  Line(Point* point_a, Point* point_b) : point_a_(point_a), point_b_(point_b) {}

  double Distance();

private:
  Point* point_a_;
  Point* point_b_;
};

int main (int argc, char * const argv[]) {
  Point point_a(0,0,0);
  Point point_b(1,1,1);
  Line line(&point_a,&point_b);
  std::cout<<line.Distance()<<"\n";

  point_a.x = 1;
  std::cout<<line.Distance()<<"\n";
}

任何反馈,不胜感激!

谢谢!

[编辑]速度在我的软件中至关重要!

最佳答案

在这种简单的情况下,我可能只使用公共(public)成员变量。

否则,我将提供返回const引用和匹配setter的getter。

class Line {
public:
    Line(const Point& p1, const Point&p2) : m_p1(p1), m_p2(p2) {}

    const Point& p1() const
    { return m_p1; }

    const Point& p2() const
    { return m_p2; }

    void setP1(const Point& p1)
    { m_p1 = p1; }

    void setP2(const Point& p2)
    { m_p2 = p2; }

private:
    Point m_p1;
    Point m_p2;
};

10-04 13:17