gpt4 book ai didi

c++ - 自定义结构和关系重载生成错误

转载 作者:行者123 更新时间:2023-11-28 03:39:50 27 4
gpt4 key购买 nike

我有以下代码,但出现错误:“错误 C2676:二进制‘>’:‘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;
}

最佳答案

您没有为 Car 定义 operator>。编译器不知道如何评估 (vec[i] > 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

更新:

因为你有一个可用的比较函数,你不需要写一个运算符>。相反,请使用您的比较功能:

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

关于c++ - 自定义结构和关系重载生成错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9629427/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com