【发布时间】: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;
}
【问题讨论】: