没有运算符 "+=" 与这些操作数匹配

No operator “+=” matches these operands

本文关键字:quot 操作数 运算符      更新时间:2023-10-16

>我有一个h文件,其中有一个名为MainControl的类,以及一个名为Vote的结构。

在 MainControl 中,我以这种方式定义一个公共运算符(这是一个成员函数):

MainControl& operator+=(Vote& v);

在匹配的.cpp文件中,我有这个功能:

MainControl& MainControl::operator+=(Vote& v){
...
}

当我尝试在另一个文件中编写类似的东西时:

mc+=v

其中mc是来自类 MainControl 的对象,v 是来自结构Vote的对象。

我收到此错误:

error C2679: binary '+=': no operator found which takes a right-hand operand of type 'Vote' (or there is no acceptable conversion)

我确实包含了我所相信的正确文件,因为我有一个非常相似的运算符为我工作(而不是结构Vote它涉及另一个类)。

我不知道是什么原因造成的,有人可以帮忙吗?

编辑:

运算符的使用方式如下:

mc += Vote(vr1, "Cyprus");

mc来自类MainControl的地方。

结构投票如下所示:

struct Vote
{
Voter voter;
string* voted_state;
// ALL is public here.
Vote(Voter current_voter, string state1, string state2 = "", string state3 = "", string state4 = "", string state5 = "", string state6 = "", string state7 = "", string state8 = "", string state9 = "", string state10 = "") :
voter(current_voter), voted_state(new string[VOTE_ARRAY_SIZE]){
voted_state[0] = state1;
voted_state[1] = state2;
voted_state[2] = state3;
voted_state[3] = state4;
voted_state[4] = state5;
voted_state[5] = state6;
voted_state[6] = state7;
voted_state[7] = state8;
voted_state[8] = state9;
voted_state[9] = state10;
}
~Vote() {
delete[] voted_state;
}
};

在不给我编译错误的类似操作中,运算符是这样使用的:

mc += p1

其中p1是类名参与者中的对象,mc 是类MainControl中的对象。

在我定义类的 .h 文件中,MainControl我有这个标记:

MainControl& operator+=(Participant& p);

课程参与者如下所示:

class Participant
{
string state_name;
string song_name;
int time_length;
string singer_name;
bool is_registered;
public:
Participant(string state, string song, int time, string singer):
state_name(state),song_name(song),singer_name(singer),time_length(time),is_registered(false){
}
~Participant() = default;
string state() const;
string song() const;
int timeLength() const;
string singer() const;
int isRegistered() const; 
void update(const string song, const int time, const string singer);
void updateRegistered(const bool status);
};

p1是这样定义的:

Participant p1("USA", "Song_USA", 175, "Singer_USA");

您的 += 运算符采用(非常量)L 值引用

MainControl& operator+=(Vote& v);

然后,将 r 值传递给它:

mc += Vote(vr1, "Cyprus");

这不能转换为(非恒量)L 值参考

如果您(如前所述)在此操作期间需要修改"投票",您可以执行以下操作:

auto v1 = Vote(vr1, "Cyprus");
mc += v1;

这样,您可以按预期将投票传递给运营商。

但: 这不是一个好的设计,以后会咬你。