简体   繁体   English

C ++类-派生类中的构造函数声明

[英]C++ classes - constructor declaration in derived class

Socket has a constructor that takes a winsock SOCKET as parameter and stores it in a private variable: 套接字具有一个构造函数,该构造函数将winsock SOCKET作为参数并将其存储在私有变量中:

Socket::Socket(SOCKET s) {
    this->s = s;
}

I'm trying to make a class "GameSocket" that will parse data from my Socket class: 我正在尝试创建一个“ GameSocket”类,该类将解析我的Socket类中的数据:

class GameSocket : public Socket {

protected:

    void ParseData(unsigned char* data, int size);

};

Next to these classes, I have a "Server" class that creates new sockets when needed: 在这些类旁边,我有一个“服务器”类,可以在需要时创建新的套接字:

GameSocket* Server::Accept() {

    SOCKET a = accept(s, 0, 0);
    if(a==SOCKET_ERROR) {
        return 0;
    }
    else {
        return new GameSocket(a);
    }

}

However, this gives me an error on the last "else": 但是,这给我最后一个“ else”错误:

error C2664: 'GameSocket::GameSocket' : cannot convert parameter 1 from 'SOCKET' to 'const GameSocket &'

I must be missing something with constructors when dealing with derived classes... 处理派生类时,构造函数一定缺少某些东西。

Don't go too hard on me, I'm relatively new to C++ and OOP 别太在意我,我对C ++和OOP还是比较陌生

Add in a constructor for GameSocket 添加GameSocket的构造函数

class GameSocket : public Socket {

public:

    // you need to add
    GameSocket(SOCKET s) : Socket(s) {}

protected:

    void ParseData(unsigned char* data, int size);

};

The construcotr for GameSocket must receive a SOCKET parameter and then pass it to the Socket base class in the initializer list: GameSocket的construcotr必须接收SOCKET参数,然后将其传递给初始化程序列表中的Socket基类:

class GameSocket : public Socket {
public:
    GameSocket(SOCKET s) : Socket(s) {}
    ...
};

Is there a reason why GameSocket must derive from Socket instead of holding a reference to the Socket? 为什么GameSocket必须从Socket派生而不是持有对Socket的引用是有原因的? GameSocket is (or should be) managing socket state and serialization while the low level socket interface is contained in the Socket class. 当套接字类中包含低级套接字接口时,GameSocket正在(或应该)管理套接字状态和序列化。 Your Server class could create instances of the Socket class and then pass a pointer to a GameSocket class for managing them. 您的Server类可以创建Socket类的实例,然后将指针传递给GameSocket类以对其进行管理。

class GameSocket {
public:
    GameSocket(Socket *s) : s_(s) {}
    ~GameSocket() {
        s_->close();
        delete s_;
    }
    ...
private:
    Socket *s_;
};

GameSocket* Server::Accept() {
    // accept function added to Socket class
    Socket *newSocket = serverSocket->accept();
    // create GameSocket with newly opened Socket
    return newSocket ? new GameSocket(newSocket) : NULL;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM