接口与实现相分离 (separate interface from implementation)

接口与实现相分离 (separate interface from implementation)#

当题目上要求接口与实现相分离, 一般来说分文件即可; 如果题目涉及类层次和继承则是在要求写一个抽象基类, 而其他具体类继承自它.

但实际进行分离远远不止这些, 想了解更多请阅读 《Sixteen Ways to Stack a Cat》by Bjarne Stroustup.

分文件#

[在线代码 rsf76fMff]

hello.hpp#
1#ifndef HELLO_HPP  // 头文件自包含保护
2#define HELLO_HPP
3
4void hello();  // 接口
5
6#endif
hello.cpp#
1#include "hello.hpp"
2
3#include <iostream>
4
5void hello() {  // 实现
6  std::cout << "Hello World!\n";
7}

抽象基类#

[在线代码 GMcvPseeE]

base.hpp#
 1#ifndef BASE_HPP
 2#define BASE_HPP
 3
 4class Base {
 5 public:
 6  Base()                       = default;
 7  Base(Base const&)            = default;
 8  Base& operator=(Base const&) = default;
 9  virtual ~Base()              = default;
10
11  virtual void hello() = 0;
12};
13
14#endif
concrete.hpp#
 1#ifndef CONCRETE_HPP
 2#define CONCRETE_HPP
 3
 4#include "base.hpp"
 5
 6class Concrete : public Base {
 7 public:
 8  void hello() override;
 9};
10
11#endif
concrete.cpp#
1#include "concrete.hpp"
2
3#include <iostream>
4
5void Concrete::hello() {
6  std::cout << "Hello World!\n";
7}