我在实现一个在另外两个类中的抽象类中声明的虚函数时遇到了问题,在不同的头文件中。虚拟函数C++:虚拟函数已经有一个主体
当我在类ProtocolLogin中实现ProtocolGame中已经实现的虚函数“parsePacket”时,编译器返回“函数已经有一个body”。
Error 1 error LNK2005: "private: virtual void __cdecl ProtocolGame::parsePacket(class NetworkMessage &)" ([email protected]@@[email protected]@@Z) already defined in protocolgame.obj
Error 2 error LNK2001: unresolved external symbol "public: virtual void __cdecl ProtocolLogin::parsePacket(class NetworkMessage &)" ([email protected]@@[email protected]@@Z)
然后我试图创建一个名为parseWater一个新的虚拟功能,将只在类ProtocolLogin实施,编译器返回我“功能,需要在ProtocolGame被声明”,但如果我这样做,我得到再次:“功能已经有一个身体”。所以,我只是不再遵循。请帮我理解:)
它就像一个无尽的循环。
class Protocol (Header File 1)
{
public:
explicit Protocol(Connection_ptr connection) : m_connection(connection)
virtual ~Protocol() = default;
// non-copyable
Protocol(const Protocol&) = delete;
Protocol& operator=(const Protocol&) = delete;
virtual void parsePacket(NetworkMessage&) {}
void onRecvMessage(NetworkMessage& msg); // Function that calls parsePacket
virtual void onRecvFirstMessage(NetworkMessage& msg) = 0;
class ProtocolGame final : public Protocol (Header File 2)
{
public:
// static protocol information
enum {server_sends_first = true};
enum {protocol_identifier = 0}; // Not required as we send first
enum {use_checksum = true};
static const char* protocol_name() {
return "gameworld protocol";
}
explicit ProtocolGame(Connection_ptr connection);
private:
void parsePacket(NetworkMessage& msg) final; //implementation //Works
void onRecvFirstMessage(NetworkMessage& msg) final; //implementation //Works
class ProtocolLogin final : public Protocol (Header File 3)
{
public:
// static protocol information
enum {server_sends_first = false};
enum {protocol_identifier = 0x01};
enum {use_checksum = true};
static const char* protocol_name() {
return "login protocol";
}
explicit ProtocolLogin(Connection_ptr connection) : Protocol(connection) {}
void onRecvFirstMessage(NetworkMessage& msg); //work
void parsePacket(NetworkMessage& msg); // dont work
不清楚的码是真正的码,什么是真正的错误。请按原样提供代码,并按错误报告的行填入错误。在附注中,您最终使用代码的目的是什么?我相信这是一个不好的做法。 – SergeyA
首先,'void onRecvLiquid();'不是虚拟 – StoryTeller
[MCVE](http://stackoverflow.com/help/mcve)。 –