抽象类

参考:https://www.cnblogs.com/main404/p/11141938.html

1. 纯虚函数

形式: virtual 函数原型 = 0;

定义: 在定义一个表达抽象概念的基类时,有时无法给出某些函数的具体实现方法,就可以将这些函数声明为纯虚函数。

特点:无具体实现方法。

2. 抽象类

定义:声明了纯虚函数的类,都成为抽象类

主要特点:抽象类只能作为基类类派生新类,不能声明抽象类的对象。(既然都是抽象概念了,纯虚函数没有具体实现方法,故不能创造该类的实际对象) 但是可以声明指向抽象类的指针变量或者引用变量,通过指针或者引用,就可以指向并访问派生类对象,进而访问派生类的成员。(体现了多态性

作用:因为其特点,基类只是用来继承,可以作为一个接口,具体功能在派生类中实现(接口)

#include <unistd.h>

// 定义了一个文件描述符接口的抽象类。其中Read() 和 Write() 为纯虚函数,供其子类实现 
// 其本身只实现了对文件描述符的设置与关闭操作。
class FileDescriptorInterface{
public:
  FileDescriptorInterface() = default;
  FileDescriptorInterface( const FileDescriptorInterface& fdInterface) = delete;
  void operator=( const FileDescriptorInterface& fdInterface ) = delete;
  FileDescriptorInterface( const int fd, const bool auto_close );

  virtual ~FileDescriptorInterface();
  virtual void setFd( const int fd );
  virtual int getFd() const { return fd_; }

  virtual int Read( void* buffer, const int nbytes ) const = 0;
  virtual int Write( const void* buffer, const int nbytes ) = 0;
  virtual int Close();

  void setClosed() { closed_ = true; }
  bool closed() const { return  closed_; }

protected:
  unsigned int fd_ = -1;
  bool closed_ = true;
  bool auto_close_ = true;
};

FileDescriptorInterface::FileDescriptorInterface( const int fd, const bool auto_close):
    auto_close_( auto_close )
{
    setFd( fd );
}

FileDescriptorInterface::~FileDescriptorInterface() {
    Close();
}

void FileDescriptorInterface::setFd(const int fd) {
    if (fd > 0) {
        fd_ = fd;
        closed_ = false;
    }
}

int FileDescriptorInterface::Close() {
    if (auto_close_ && !closed_ && fd_ > 0) {
        close(fd_);
        closed_ = true;
        return 0;
    }
    return -1;
}

  

原文地址:https://www.cnblogs.com/zengtx/p/11942850.html