C++笔记02

71 阅读1分钟

本章主要讲面向对象(Object Oriented Programming)编程。

对象间有三个重要的关系

  • Inheritance(继承)
  • Composition(复合)
  • Delegation(委托)

Composition,表示 has a

管这种类又叫做Adapter

template <class T, class Sequence = deque<T>>
class queue
{
    ...
protected:
    Sequence c;//底层容器
public:
    //以下完全利用c的操作函数完成
    bool empty() const {return c.empty();}
    size_type size() const {return c.size();}
    reference front() {return c.front();}
    reference back() {return c.back();}
    //deque是两端可进出,queue是末端进前端出(先进先出)
    void push(const value_type& x) {c.push_back(x);}
    void pop() {c.pop_front();}
};

image.png

Delegation(委托),Composition by reference

//file String.hpp
class StringRep;
class String
{
public:
    String();
    String(const char* s);
    String(const String& s);
    String &operator=(const String& s);
    ~String();
...
private:
    StringRep* rep;//pimpl
};
//file String.cpp
#include "String.hpp"
namespace
{
class StringRep
{
friend class String;
    StringRep(const char* s);
    ~StringRep();
    int count;
    char* rep;
};
}

String::String(){...}
...

这种手法可称为编译防火墙

image.png

Inheritance(继承),表示 is-a

struct _List_node_base
{
    _List_node_base* _M_next;
    _List_node_base* _M_prev;
};

template<typename _Tp>
struct _List_node:public _List_node_base
{
    _Tp _M_data;
};

image.png

继承中的虚函数

函数有三种类型:

non-virtual函数:不希望derived class重新定义(override,复写)它。
virtual函数:希望derived class重新定义(override,复写)它,它已有默认定义。
pure virtual函数:希望derived class一定要重新定义(override)它,对它没有默认定义。