在初始化时无法将'object *'转换为'abstract *'

时间:2016-07-14 09:50:27

标签: c++ oop pointers abstract-class derived-class

我正在尝试使用服务器接口来处理多个服务器,具体取决于哪个服务器可用。简化后,代码如下:

Server.h

class Server : public ServerInterface {
public:
    Server();
    static Server * getServerPtr();
}

Server.cpp

#include "Server.h"

Server::Server () {}

Server * Server::getServerPtr() {
    Server * server = new Server();
    return server;
}

HMDServer.h

class HMDServer : public ServerInterface {
public:
    HMDServer();

    static HMDServer * getHMDServerPtr();

    void init();

private:
    int server_type;

HMDServer.cpp

#include "HMDServer.h"

HMDServer::HMDServer() {
    server_type = 1;
    init();
}

HMDServer * HMDServer::returnHMDServerPtr() {
    HMDServer * server = new HMDServer();
    return server;
}

void HMDServer::init() {
    //try to initialize server
    server_type = 111; // if initialization successful
}

ServerInterface.h

class ServerInterface {
public:
    static ServerInterface * getServer();
}

ServerInterface.cpp

#include "ServerInterface.h"
#include "HMDServer.cpp"
#include "Server.cpp"

ServerInterface * ServerInterface::getServer() {
    ServerInterface * server1 = HMDServer::getHMDServerPtr(); //This works perfectly
    if(server1->getServerType() == 1) {
        ServerInterface * server2 = Server::getServerPtr();
        return server2;
    } else
        return server1;
}

的main.cpp

#include "ServerInterface.cpp"

int main() {

    ServerInterface * server = ServerInterface::getServer();

    return 0;
}

当我运行此代码时,它进入getServer()的if函数,当它尝试从Server类获取指针时,我收到一条错误说: cannot convert 'Server*' to 'ServerInterface*' in initialization. 以前,在我添加服务器文件之前,只包含了HMDServer,它运行得很完美。我做错了什么?

1 个答案:

答案 0 :(得分:0)

不确定这是拼写错误还是实际存在于您的代码中,但在ServerInterface.cpp中,您说明了以下内容:

#include "HMDServer.cpp"
#include "Server.cpp"

如果您确实包含.cpp个文件而不是实际的标头,则可能会出现奇怪的行为。

也是如此
#include "ServerInterface.cpp"

main.cpp