假设我有纯抽象类IHandler和派生自它的类:
class IHandler
{
public:
virtual int process_input(char input) = 0;
};
class MyEngine : protected IHandler
{
public:
virtual int process_input(char input) { /* implementation */ }
};
我想在我的 MyEngine 中继承该类,以便我可以传递MyEngine*给任何期望IHandler*并让他们能够使用process_input. 但是我不想允许访问,MyEngine*因为我不想公开实现细节。
MyEngine* ptr = new MyEngine();
ptr->process_input('a'); //NOT POSSIBLE
static_cast<IHandler*>(ptr)->process_input('a'); //OK
IHandler* ptr2 = ptr; //OK
ptr2->process_input('a'); //OK
这可以通过受保护的继承和隐式转换来完成吗?我只设法得到:
从“MyEngine *”到“IHandler *”的转换存在,但无法访问
由于我来自 C# 背景,这基本上是 C# 中的显式接口实现。这是 C++ 中的有效方法吗?
额外的:
为了更好地了解我为什么要这样做,请考虑以下几点:
类TcpConnection通过 TCP 实现通信,并且在其构造函数中需要指向 interface 的指针ITcpEventHandler。当TcpConnection在套接字上获取一些数据时,它将该数据传递给它的ITcpEventHandlerusing ITcpEventHandler::incomingData,或者当它轮询它使用的传出数据时ITcpEventHandler::getOutgoingData。
我的类HttpClient使用TcpConnection(聚合)并将自身传递给TcpConnection构造函数,并在这些接口方法中进行处理。
所以TcpConnection必须实现这些方法,但我不希望用户使用HttpClient直接访问ITcpEventHandler方法(incomingData,getOutgoingData)。他们应该不能打电话incomingData或getOutgoingData直接打电话。
希望这能澄清我的用例。