问题描述
#include <iostream>
#include <list>
using namespace std;
struct DATA
{
int d;
int d2;
};
int main()
{
DATA d1;
d1.d = 100;
d1.d2 = 200;
list<DATA> ld;
ld.push_back(d1);
ld.remove(d1);
}
1>------ Build started: Project: ConsoleApplication2_List,Configuration: Debug Win32 ------
1>ConsoleApplication2_List.cpp
1>C:\Program Files (x86)\Microsoft Visual Studio\2019\Professional\VC\Tools\MSVC\14.27.29110\include\list(1603,65): error C2676: binary '==': 'const _Ty' does not define this operator or a conversion to a type acceptable to the predefined operator
1> with
1> [
1> _Ty=DATA
1> ]
1>C:\Program Files (x86)\Microsoft Visual Studio\2019\Professional\VC\Tools\MSVC\14.27.29110\include\list(1602): message : while compiling class template member function 'auto std::list<DATA,std::allocator<DATA>>::remove(const _Ty &)'
1> with
1> [
1> _Ty=DATA
1> ]
1>C:\TestCode\ConsoleApplication2_List\ConsoleApplication2_List\ConsoleApplication2_List.cpp(17): message : see reference to class template instantiation 'std::list<DATA,std::allocator<DATA>>' being compiled
1>C:\Program Files (x86)\Microsoft Visual Studio\2019\Professional\VC\Tools\MSVC\14.27.29110\include\list(1614,1): error C2451: conditional expression of type 'void' is illegal
1>C:\Program Files (x86)\Microsoft Visual Studio\2019\Professional\VC\Tools\MSVC\14.27.29110\include\list(1614,22): message : Expressions of type void cannot be converted to other types
1>C:\Program Files (x86)\Microsoft Visual Studio\2019\Professional\VC\Tools\MSVC\14.27.29110\include\list(1603): message : see reference to function template instantiation 'auto std::list<DATA,std::allocator<DATA>>::remove_if<std::list<DATA,std::allocator<DATA>>::remove::<lambda_c489c5225c742bd5c5073b600e1d767b>>(_Pr1)' being compiled
1> with
1> [
1> _Pr1=std::list<DATA,std::allocator<DATA>>::remove::<lambda_c489c5225c742bd5c5073b600e1d767b>
1> ]
1>Done building project "ConsoleApplication2_List.vcxproj" -- Failed.
========== Build: 0 succeeded,1 Failed,0 up-to-date,0 skipped ==========
我创建了一个C ++程序,该程序使用包含自定义类型list
的{{1}},可以很好地添加数据,但是当我调用struct data
函数时,编译器会产生上述错误
我该如何解决这个问题?
解决方法
错误消息告诉您,您需要operator==
来检查是否相等。这样remove
函数将知道要删除哪些元素。
struct DATA
{
int d;
int d2;
bool operator==(const DATA& other) const {
return d == other.d && d2 == other.d2;
}
};
修改
正如Jens所指出的,将操作数定义为自由函数通常是一个好主意。这是由于这样的事实,即运算符的右侧和左侧都可以隐式转换为正确的类型。与成员函数相比,成员函数只有运算符的右侧才能隐式转换。
在这种特定情况下,这没有什么区别,但总的来说,这是一个很好的经验法则。
struct DATA
{
int d;
int d2;
};
bool operator==(const DATA& lhs,const DATA& rhs) {
return lhs.d == rhs.d && lhs.d2 == rhs.d2;
}
,
根据以下错误消息,struct DATA
需要一个==
运算符方法:
C:\Program Files (x86)\Microsoft Visual Studio\2019\Professional\VC\Tools\MSVC\14.27.29110\include\list(1603,65): error C2676: binary '==': 'const _Ty' does not define this operator or a conversion to a type acceptable to the predefined operator