简体   繁体   中英

C++ inheritance design: avoid member duplication

Let's assume that one has two C++ classes that support read-only and write-only operations on a file descriptor respectively.

class ReadFd {
 public:
  ssize_t read( /* */ ) {
    // read from file_descriptor_
  }
 protected:
  int file_descriptor_;
};

class WriteFd {
 public:
  ssize_t write(/* */) {
    // write to file_descriptor_
  }
 protected:
  int file_descriptor_;
};

Now suppose one would like to define a class ReadWriteFd that supports both read and write operations.

My question is how to design such read-write class to avoid code duplication?

I cannot inherit from both ReadFd and WriteFd because obviously I need just one file_descriptor_ . The real situation that I encountered a bit more complicated but the concept here reflects it rather close.

添加第三个类,基于ReadFdWriteFd ,其唯一目的是包含描述符变量(可能还包括读写共享的其他内容)。

Create a new base class called class Fd which contains the file descriptor. class ReadFd & WriteFd can both inherit from it with an is-a relationship. Your ReadWriteFd can inherit from these 2 classes. Just remember that you will have to solve the diamond multiple inheritance problem .

Here is an example UML:

在此输入图像描述

As OO Principals state:

Encapsulate what varies. – can be rephrased as “Identify the aspects of your application that vary and separate them from what stays the same.” For those aspects that don't change, we leave them as they are. Of course, we can't just throw away those parts that vary; the former still needs to interact with them in order for the system to work.
In your particular case you can create a base class with common data and interfaces.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM