向类中添加功能可以通过添加一个方法或定义一个将对象作为其第一个参数的函数来完成。我知道大多数程序员会选择添加实例方法的解决方案。在实例方法和自由函数之间进行选择?
但是,我有时更喜欢创建一个单独的函数。例如,在下面的示例代码中,将Area
和Diagonal
定义为自由函数而不是方法。我觉得这样更好,因为我认为这些功能提供了增强功能,而不是核心功能。
这是否被认为是好的/坏的做法?如果答案是“取决于”,那么决定添加方法或定义单独函数的规则是什么?
class Rect
{
public:
Rect(int x, int y, int w, int h) :
mX(x), mY(y), mWidth(w), mHeight(h)
{
}
int x() const { return mX; }
int y() const { return mY; }
int width() const { return mWidth; }
int height() const { return mHeight; }
private:
int mX, mY, mWidth, mHeight;
};
int Area(const Rect & inRect)
{
return inRect.width() * inRect.height();
}
float Diagonal(const Rect & inRect)
{
return std::sqrt(std::pow(static_cast<float>(inRect.width()), 2) + std::pow(static_cast<float>(inRect.height()), 2));
}
一个侧面说明,使用pow的恒定幂数是2,相对于自己拼出x * x + y * y + z * z的效率极低。 – 2010-04-06 19:38:57
@Mark B:谢谢,我不知道。 – StackedCrooked 2010-04-06 21:34:31
查看经典_ [非成员函数如何改进封装](http://drdobbs.com/cpp/184401197)_。 (“当你认为封装时,你应该考虑非成员函数”)另见http://stackoverflow.com/q/1692084/140719。 – sbi 2011-11-25 10:29:09