[英]Error: No viable overloaded =
I have a class which looks like this: 我有一堂课,看起来像这样:
class MemberListEntry {
public:
int id;
short port;
long heartbeat;
long timestamp;
MemberListEntry(int id, short port, long heartbeat, long timestamp);
MemberListEntry(int id, short port);
MemberListEntry(): id(0), port(0), heartbeat(0), timestamp(0) {}
MemberListEntry(const MemberListEntry &anotherMLE);
MemberListEntry& operator =(const MemberListEntry &anotherMLE);
int getid();
short getport();
long getheartbeat();
long gettimestamp();
void setid(int id);
void setport(short port);
void setheartbeat(long hearbeat);
void settimestamp(long timestamp);
};
The I have some code which instantiates it like this: 我有一些将其实例化的代码:
int id = stoi(address.substr(0, pos));
short port = (short)stoi(address.substr(pos + 1, address.size()-pos-1));
memcpy(&addr[0], &id, sizeof(int));
memcpy(&addr[4], &port, sizeof(short));
MemberListEntry mEntry;
mEntry = new MemberListEntry(id, port);
I am getting this error: 我收到此错误:
error: no viable overloaded '='
mEntry = new MemberListEntry(id, port);
Any idea what could be the cause of the issue? 任何想法可能是问题的原因吗?
Your code should be 您的代码应为
MemberListEntry * mEntry;
mEntry = new MemberListEntry(id, port);
You are allocating an object on heap using new operator which returns pointer to the object created and you are trying to assign a pointer to an object. 您正在使用new运算符在堆上分配对象,该运算符返回指向创建的对象的指针,并且尝试分配指向对象的指针。
Better alternative here would be allocate object on stack which you are doing it already. 更好的替代方法是在堆栈上分配已经在做的对象。
MemberListEntry mEntry(id, port);
This creates and initializes the object and it will be destructed automatically when your function goes out of scope. 这将创建并初始化对象,并且当您的函数超出范围时,它将自动销毁。
Fun fact: This not java, it's C++. 有趣的事实:这不是Java,而是C ++。 :) :)
Hope this helps. 希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.