昨天做比赛的时候发现了一个奇怪bug,下面是我写的一个测试程序,
运行后会显示:
[Error] no match for 'operator==' (operand types are '__gnu_cxx::__alloc_traits<std::allocator<node> >::value_type {aka node}' and 'node')
环境是Dev 5.11,这判断符两边的数据类型是一样的啊,为什么会报错?求解答
#include <iostream>
#include <vector>
using namespace std;
struct node
{
int k;
};
int main()
{
vector<node>a(7);
a[3].k=0;
node t;
t.k=0;
if(a[3]==t)
{
cout<<"1";
}
else
{
cout<<"0";
}
}
没有重载 == 符号
解决方法:
#include <iostream>
#include <vector>
using namespace std;
struct node
{
int k;
operator == (node b) {
return (this->k == b.k);
}
};
int main()
{
vector<node>a(7);
a[3].k=0;
node t;
t.k=0;
if(a[3]==t)
{
cout<<"1";
}
else
{
cout<<"0";
}
}
不懂再问
望采纳,谢谢
node 没有重载 ==操作符
struct node
{
int k;
bool operator ==(node &nd)
{
return (k == nd.k);
}
};
你这个编译是有问题的 if(a[3]==t)这一行错了,因为a[3]和t 都是struct node结构体变量,而C和C++规定比较符号只能作用于基本数据类型(包括int,char,float,double,bool,以及与之组合的unsigned short long 等),结构体,共用体等,不属于基本类型,所以C和C++肯定是不支持的,如果实在想比较的话,可以将他们的成名变量一个个比较,比如写成 if(a[3].k==t.k),这样是没有问题的,另外相同结构体变量之间是可以直接赋值的,也就是你可以直接写成a[3] = t,或者t =a[3], 这是没问题的