如何声明运算符重载<在需要时动态地在类变量之间切换?

时间:2016-01-11 19:10:39

标签: c++ oop operator-overloading

我一直在搜索很多网站并浏览了一些关于此的书籍,但未能找到关于如何动态地(在程序执行期间)比较不同数据类型的实现的良好来源与 less-< 大于> 运营商。

我们说我们有以下代码段:

#include <iostream>

using namespace std;

class OP
{
private:
    string alias;
    float locatorX;
    int coordinate;
public:
    bool operator<(const OP& rhs)
    {
        return (this->locatorX < rhs.locatorX);
        //Here! How do I do to make the compiler understand that
        //I compare i.e alias or coordinate whenever I need? 
        //I tried with:
            return (this->coordinate < rhs.coordinate, this->alias < rhs.alias);
        //But it didn't really do the trick when implemented 
        //a sort algorithm inside main as it failed to sort a string array.
    }
};

修改

由于这里的大多数人都不明白这个问题,所以这是一个你希望得到的情景。

我们假设我们要创建一个接受字符串,int和float类型的映射。我们在类OP中创建一个函数,它接受所有给定的数据类型并将它们保存在创建的类数组中。所以我们在类数组中有15条记录。

我该如何操作,我可以使用小于运算符的升序动态冒泡排序(使用&lt;运算符),别名(字符串)locatorX(float)和坐标(int)(无论我选择哪个)? / p>

例如,我有时需要在运行时对坐标或别名(如果需要)进行排序。我该怎么做?

示例输出:

(数组中的第一个位置):

&#34; Albert street 5th&#34;

协调:1691

locatorX:19.52165

(数组中的第二个位置):

&#34;主要街道7号胡同&#34;

协调:59

locatorX:8175。12

(数组中的第三个位置):

&#34;榆树/肯塔基州&#34;

协调:9517

locatorX:271.41

2 个答案:

答案 0 :(得分:3)

通常,您要为要实现的每个比较创建一个单独的比较器。你不能将它们组合成一个operator<,虽然你可以在技术上产生一个不同的函数,根据一些新的第三个参数的值进行不同的比较,但它几乎与现有的几乎所有东西都不相容。知道如何使用比较器。

这是运算符重载特定的错误工具之一。

答案 1 :(得分:1)

似乎有几种方法可以这样做:

在呼叫站点

之间切换比较功能

您必须为不同的字段定义单独的比较函数。

std::vector<Object> v;

enum class OrderBy
{
    alias,
    coordinate
}

OrderBy order_by = get_orderBy_from_user();

switch (order_by)
{
case OrderBy::alias:
    std::sort(v.begin(), v.end(), compare_by_alias());
    break;
case OrderBy::coordinate:
    std::sort(v.begin(), v.end(), compare_by_coordinate());
    break;
}

在比较功能中做出选择。

您必须以某种方式将订购字段的选择传达给函数。 选项包括:全局或单身&#34;配置&#34; object,比较类中的成员变量。我会避免任何全局变量,因此第二个选项:

struct compare_by_field
{
    OrderBy order_by_;

    compare_by_field(OrderBy order_by) : order_by_(order_by)
    {}

    bool operator()(const Object & lhs, const Object & rhs) const
    {
        switch (order_by_)
        {
        case OrderBy::alias:
            return lhs.alias < rhs.alias;
        case OrderBy::coordinate:
            return lhs.coordinate < rhs.coordinate;
        }
    }
}

std::sort(v.begin(), v.end(), compare_by_field(get_order_by_from_user()));