【发布时间】:2019-06-15 21:11:10
【问题描述】:
我有一个 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 类。
结构体 Vote 如下所示:
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 的对象。
在我定义类 MainControl 的 .h 文件中,我有这个错误:
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");
【问题讨论】:
-
评论不用于扩展讨论;这个对话是moved to chat。