0
假设我们有类名默认值有两个属性x和y。
比较对象的默认操作是使用属性x。运算符重载和类型转换
当我们想使用其他属性y以比较这对象,
1.是否安全,创造新的派生类,可以通过使用属性y,然后浇注指针从默认新课改比较,比较的对象?
2.在不降低操作性能的情况下,采取何种替代方法?
要求是我们不能改变排序算法的签名,把函数指针传递给差分比较器。
顺便说一下,这种方法是不需要转换或复制数据的成本。
class Default {public:int x; int y;};
class Compare1 : public Default {};
bool operator < (const Default &left,const Default &right)
{
return left.x < right.x;
}
bool operator < (const Compare1 &left,const Compare1 &right)
{
return left.y < right.y;
}
template<typename T>
int *sort_element(const T *data, int size)
{
int *permute;
//... do some sorting by using < comparator ...
return permute;
}
int main(){
Default *obj;
int obj_size;
//… initialize obj and obj size..
// sorting object with default order.
int *output_default = sort_element(obj, obj_size)
// sorting with customize comparator.
Compare1 *custom1 = static_cast<Compare1*>(obj);
int *output_custom1 = sort_element(custom1, obj_size);
}
听起来不错,但有一种情况是我不能更改函数sort_element的头。 – unbound
如果你不能那么很遗憾你没有选择,你的代码是唯一的选择,那么你应该停止担心效率。 – deepmax