【问题标题】:custom struct & relational overload generating error自定义结构和关系重载生成错误
【发布时间】:2012-03-09 05:36:05
【问题描述】:

我有以下代码并收到错误消息: “错误 C2676: binary '>' : 'const Car' 没有定义此运算符或转换为预定义运算符可接受的类型”

它出现在:if (vec[i] > returnValue) /.../ 行

我知道它可能对如何比较 Car 结构感到困惑,但最后一个回调/重载函数不应该解决这个问题吗?有什么建议吗?

#include <vector>
#include <iostream>
#include <string>

struct Car {
    std::string name;
    int weight;
    int airbags;
};

//callback for typical compairsons
template <typename Type>
int CmpCallBack(Type one, Type two) {
    if (one < two) return -1;
    if (one == two) return 0;
    if (one > two) return 1;
}

//itterate through vec<Type> and return max value
template <typename Type>
Type FindMax(std::vector<Type> const &vec, int (cmpFn)(Type one, Type two) = CmpCallBack) {
    Type returnValue = new Type; //is this the right way to initialize this var?
    for (int i = 0; i < vec.size(); i++) {
        if (vec[i] > returnValue) {
            returnValue = vec[i];
        }
    }
    return returnValue;
}

//callback for the custom "Car" struct
int CarAirComp(Car one, Car two) {
    if (one.airbags < two.airbags) return -1;
    if (one.airbags == two.airbags) return 0;
    if (one.airbags > two.airbags) return 1;
}

int main () {

        //build a vector of Car types
    std::vector<Car> cars;
    Car x;
    x.airbags = 5;
    x.name = "car one";
    Car y;
    y.airbags = 3;
    y.name = "car two";
    Car z;
    z.airbags = 1;
    z.name = "car three";
    cars.push_back(x);
    cars.push_back(y);
    cars.push_back(z);

        //test function
    Car returnVal = FindMax(cars, CarAirComp);

    std::cout << "value: " << returnVal.name << std::endl;

    system("pause");
    return 0;
}

【问题讨论】:

    标签: c++ templates


    【解决方案1】:

    您没有为Car 定义operator &gt;。编译器不知道如何评估(vec[i] &gt; returnValue)。如果你定义了这个运算符,你应该没问题:

    struct Car {
        ...
        bool operator >(const Car & other) const 
        {
           // compare them however you like
           return weight < other.weight; 
        }
    }
    

    此外,您还需要更改:

    Type returnValue = new Type;
    

    Type returnValue;  // this default constructs the object
    

    更新:

    因为你有一个比较功能可用,你不需要写operator &gt;。相反,请使用您的比较功能:

    if(cmpFn(vec[i], returnValue) > 0) {
        returnValue = vec[i];
    }
    

    【讨论】:

    • 上面的“bool operator >”会在模板间保持一致吗?我希望用户能够比较 Car 结构,但他/她想...这就是为什么我包含可选的比较函数“CmpCallBack”。当我在 main 中调用“FindMax”并将“CarAirCmp”参数(结构的回调)传递给它时,我希望重载“>”运算符并处理该错误。我是否将比较信息放在 Car 结构中?我在这里遗漏了一些东西......
    • 很公平,那么您应该使用该比较函数而不是 'vec[i] > returnValue'。我会更新回复以反映这一点。
    • 就是这样。没有意识到我需要在里面以函数形式调用它。现在我明白了。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2017-10-29
    • 2018-01-25
    • 2016-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-18
    相关资源
    最近更新 更多