不能继承两个继承一个接口的类



我有两个接口:SocketListeningSocket,以及实现这些接口的两个类:BerkeleySocketBerkeleyListeningSocket。将会有更多的套接字类型,现在它只是一个例子。问题是BerkeleyListeningSocket同时继承了BerkeleySocketListeingSocket。它继承了BerkeleySocket以避免处理基本套接字方法实现,继承了ListeningSocket以实现侦听套接字方法。但是类BerkeleySocket和接口ListeningSocket都继承了接口Socket,但ListeningSocket没有实现它与BerkeleySocket不同的纯虚拟方法(本例中为Close方法(,因此由于错误unimplemented pure virtual method 'Close',我无法创建BerkeleyListeningSocket的对象。说明问题的示例代码:

// This is an example code, so there will be more methods.
// ----------------
// Interfaces
// ----------------
class Socket
{
public:
virtual ~Socket() = default;
virtual void Close() = 0;
};
class ListeningSocket : public Socket
{
public:
virtual bool Listen(int max_connections) = 0;
};
// ----------------
// Implementations
// ----------------
// Implementation of base socket.
class BerkeleySocket : public Socket
{
public:
explicit BerkeleySocket(SOCKET s) : socket_(s) {}
~BerkeleySocket() override { closesocket(this->socket_); }
void Close() override { closesocket(this->socket_); }
protected:
const SOCKET socket_;
};
// Listening socket implementation.
// Inherits BerkeleySocket to avoid coping code of implementation of base socket methods, such as Close.
// There will be more derivatives of BerkeleySocket, so I can't move Close method to BerkeleyListeningSocket.
// Implements ListeningSocket interface. But there is a problem.
// Both BerkeleySocket and ListeningSocket inherits Socket interface,
// so ListeningSocket have unimplemented method Close
// and I can't create an object of BerkeleyListeningSocket because of it.
class BerkeleyListeningSocket : public BerkeleySocket, public ListeningSocket
{
public:
explicit BerkeleyListeningSocket(SOCKET s) : BerkeleySocket(s) {}
bool Listen(int max_connections) override { return listen(this->socket_, max_connections) != SOCKET_ERROR; }
};
int main() {
// Error! Unimplemented pure virtual method Close.
BerkeleyListeningSocket listening_socket(socket(AF_INET, SOCK_STREAM, IPPROTO_TCP));
return 0;
}

希望得到你的帮助!提前感谢!

这是一种需要虚拟继承的情况,因为在您的代码中,BerkeleyListeningSocketSocket继承了两次(一次从BerkeleySocket继承,一次从ListeningSocket继承(。为了告诉编译器";将两个CCD_ 21合并为一";,您需要更改类定义:

class ListeningSocket : public virtual Socket
{
// ...
};
class BerkeleySocket : public virtual Socket
{
//
};

最新更新