How to hide virtual method in C++ and keep interfa

2019-09-17 10:17发布

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.

标签: c++ oop virtual
2条回答
迷人小祖宗
2楼-- · 2019-09-17 10:28

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

http://flylib.com/books/2/253/1/html/2/images/12fig27.jpg

查看更多
一夜七次
3楼-- · 2019-09-17 10:30

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);
  }
}
查看更多
登录 后发表回答