我有一个基类Shape
和一些其他派生类,如Circle
,Rectangle
等。我想将两个对象传递给函数getDistance(object1, object2)
来计算两个对象之间的距离。以两个对象作为参数的函数
我的问题是,这个函数应该如何声明和实现?你认为我应该使用template
,因为我可能会传递来自两个不同类的两个对象吗?如果是这样,template
将如何?
任何帮助表示赞赏
我有一个基类Shape
和一些其他派生类,如Circle
,Rectangle
等。我想将两个对象传递给函数getDistance(object1, object2)
来计算两个对象之间的距离。以两个对象作为参数的函数
我的问题是,这个函数应该如何声明和实现?你认为我应该使用template
,因为我可能会传递来自两个不同类的两个对象吗?如果是这样,template
将如何?
任何帮助表示赞赏
通常你会使用一个纯虚的基类。你已经有了Shape的继承,所以模板对于这个问题来说是矫枉过正的。
添加虚拟为getPosition()到您的基本形状类并进行getDistance的()取两个形指针(或引用)。例如:
class Shape
{
public:
~virtual Shape() {} // Make sure you have a virtual destructor on base
// Assuming you have a Position struct/class
virtual Position GetPosition() const = 0;
};
class Circle : public Shape
{
public:
virtual Position GetPosition() const; // Implemented elsewhere
};
class Rectangle : public Shape
{
public:
virtual Position GetPosition() const; // Implemented elsewhere
};
float getDistance(const Shape& one, const Shape& Two)
{
// Calculate distance here by calling one.GetPosition() etc
}
// And to use it...
Circle circle;
Rectangle rectangle;
getDistance(circle, rectangle);
编辑:的Pawel Zubrycki是正确的 - 在良好的措施基类添加的虚拟析构函数。 ;)
你可以用模板做:
template<class S, class T> getDistance(const S& object1, const T& object2) {
只要两个对象具有相同的功能或变量(即x和y)来计算距离。只要Shape类迫使像功能为getPosition
getDistance(const Shape& object1, const Shape& object2)
:
getPosition() = 0; (in Shape)
我建议继承,因为这将是更清洁和更容易理解和
否则,你可以使用继承控制错误,代价是一小部分速度。
另一种选择是使用参数多态:
struct Position {
float x, y;
};
class Circle {
public:
Position GetPosition() const; // Implemented elsewhere
};
class Rectangle {
public:
Position GetPosition() const; // Implemented elsewhere
};
float getDistance(const Position &oneP, const Position twoP); // Implemented elsewhere
template<class K, class U>
float getDistance(const K& one, const U& two) {
return getDistance(one.GetPosition(), two.GetPosition());
}
哇,那是异想天开。我的课程与您发布的内容略有不同,但您的观点让我领悟到了解决方案。谢谢Scotty :) – 2012-07-23 06:06:54
@JackintheBox:不客气。你可以点击接受我的答案吗? :) – Scotty 2012-07-23 06:52:13
'Shape'类应该有虚拟析构函数。 – 2012-07-23 06:55:54