[英]Advice on c++ class interface design: how would you name these two methods to make them obvious?
我有一個非常簡單的具體 class 表示 2D 空間中的一個點,它有兩種方法來移動給定半徑和角度的點:一種修改 object 本身,另一種創建另一個 ZA8CFDE6331BD59EB2AC96F8911C4B666 不變:
template<class T =double> class cls_2DPoint
{
...
cls_2DPoint<T>& polar_move(const T r, const double a) noexcept
{
x+=r*std::cos(a); y+=r*std::sin(a); return *this;
}
cls_2DPoint<T> polar_moved(const T r, const double a) const noexcept
{
return cls_2DPoint<T>(x+r*std::cos(a), y+r*std::sin(a));
}
...
T x,y;
};
這實際上是我正在使用的代碼:在查看它時,我意識到這是一個魯莽的設計,不明顯,容易出錯。 使用戶代碼的可讀性降低,因為我正在努力尋找一個令人信服的替代方案:我想在這里征求意見? 是否有命名修改和非修改方法的一般約定/指南? 是否有可以幫助我改進設計的最佳實踐?
我的建議。
namespace
而不是 class 名稱的前綴namespace cls2D
{
class Point { ... };
}
Vector
namespace cls2D
{
class Point { ... };
class Vector { ... };
}
定義與兩種 object 類型一起使用的運算符方法。 如果您可以擺脫它,請首選非成員函數。
namespace cls2D
{
class Vector;
class Point
{
public:
Point& operator+=(Vector v);
Point& operator-=(Vector v);
private:
double x = 0;
double y = 0;
};
class Vector
{
public:
Vector& operator+=(Vector v);
Vector& operator-=(Vector v);
private:
double x = 0;
double y = 0;
};
Point from_polar(double r, double th);
Point from_vector(Vector v);
Vector from_point(Point p);
Point operator+(Point p, Vector v);
Point operator+(Vector v, Point p);
Vector operator+(Vector v1, Vector v2);
Vector operator-(Point p1, Point p2);
Vector operator-(Vector v1, Vector v2);
}
請注意, Point
和Vector
具有相同的成員數據。 因此,很容易只使用一個 class 來代表兩者。 但是,我認為它們是兩個不同的抽象,應該是不同的類。
我刪除了答案中的template
部分,以使這個想法的說明更簡單。
我假設您知道如何將必要的構造函數添加到類中。
我會這樣命名它們:
template<class T =double> class cls_2DPoint
{
...
cls_2DPoint<T>& polarMovePoint(const T r, const double a) noexcept
{
x+=r*std::cos(a); y+=r*std::sin(a); return *this;
}
cls_2DPoint<T> polarMovePointClone(const T r, const double a) const noexcept
{
return cls_2DPoint<T>(x+r*std::cos(a), y+r*std::sin(a));
}
...
T x,y;
};
這種類型的標簽會讓我知道哪個 function 移動點本身,哪個 function 創建點的克隆而不是移動那個點。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.