我在實現一個在另外兩個類中的抽象類中聲明的虛函數時遇到了問題,在不同的頭文件中。虛擬函數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)。 –