How to hide virtual method in C++ and keep interface?

懵懂的女人 提交于 2019-12-11 17:33:41

问题


I want make a SharedInterrupt class(B) which will serve in series many objects in one interrupt vector. But the derived classes(C..) of SharedInterrupt class(B) must have same ISR() function(func) as SingleInterrupt class(A). Is it possible?

class A {
public:
virtual void func() = 0;
};

class B : public A {
private:
void func() // I want to hide this method from derived classes (C, etc.)
{
// some code
}

public:
virtual void func() = 0; // And I want to keep A's interface, but compiler error!

};

class C : public B {
public:
void func() {
// some other code
}

};

P.S. Now I have only one idea to hide, make intermediate subclass from B to hide A::func() and inherits C from it.


回答1:


Composition, rather than inhertance, is the only way to get this right in C++.

This pattern uses an abstract base class (IStream) that defines the interface. A common instance of this problem is when trying to implement an "OnRead" callback on both a socket class, and later an SSL wrapper, and perhaps later, some kind of application layer "packet" is ready.

An implementation might look like this - note the extra bonus advantage of this approach is the ability to swap out parts of the chain that might be optional (so, in the case of a communications class as presented, one can plug in optional compression or encryption modules).

struct IStream {
  virtual OnRead()=0;
};

class Socket : IStream {
  IStream* _delegate;
protected:
  virtual OnRead(){
    while(ReadBytes())
      _delegate->OnRead();
  }
public:
  Socket(IStream* delegate):_delegate(delegate){}
};

class SSLSocket : IStream {
  Socket* _socket;
  IStream* _delegate;
protected:
  virtual OnRead(){
    while(ReadSslRecord())
      _delegate->OnRead();
  }
 public:
  SslSocket(IStream* delegate):_delegate(delegate),_socket(new Socket(this)){}
};

class AppSocket : IStream {
  IStream* _socket;
public:
  AppSocket(bool useSsl){
    _socket = useSsl?new SslSocket(this):new Socket(this);
  }
}



回答2:


You can try something using inheritance access specifiers. If you don't know how it works, look at this:



来源:https://stackoverflow.com/questions/11898245/how-to-hide-virtual-method-in-c-and-keep-interface

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!