C++实现设计模式: PIMPL IDIOM

本文介绍了从《Professional C++》一书中学习到的PIMPL IDIOM设计模式,并通过一个SpreadsheetCell类的实例展示了其实现。该设计模式紧凑且实用,适用于未来的工程实践。文章包含了类的UML图,以及相关操作符的定义,如加减乘除等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

I learned this from the book  Professional C++. And code this example to deepen the this practical pattern.
The whole design is very compact, and very practical. I think that it is very suitable for applications in the future as an example of engineering practice. Hope you like it.

I have drew the UML class diagrams  for overview the classes:


SpreadsheetCell.h
#ifndef SPREAD_SHEET_CELL_H
#define SPREAD_SHEET_CELL_H

#include <iostream>
#include <string>
#include <sstream>
using namespace std;

class Spreadsheet;

class SpreadsheetCell
{
public:
    typedef enum {Red=1, Green, Blue, Yellow} Colors;
    
    SpreadsheetCell& operator+=(const SpreadsheetCell& rhs);
    SpreadsheetCell& operator-=(const SpreadsheetCell& rhs);
    SpreadsheetCell& operator*=(const SpreadsheetCell& rhs);
    SpreadsheetCell& operator/=(const SpreadsheetCell& rhs);
    const SpreadsheetCell operator-() const;
    
    SpreadsheetCell(double initialValue = 0.0);
    explicit SpreadsheetCell(const string& initialValue);
    SpreadsheetCell(const SpreadsheetCell& src);
    SpreadsheetCell& operator=(const SpreadsheetCell& rhs);
    
    void set(double inValue);
    void set(const string& inString);
    void setColor(Colors color);

    double getValue() const;
    string getString() const;
    
    const SpreadsheetCell operator+(const SpreadsheetCell& cell) const;
    const SpreadsheetCell operator+(double rhs) const;
    SpreadsheetCell& operator++(); //Prefix
    SpreadsheetCell& operator--(); //Prefix
    SpreadsheetCell operator++(int); //Postfix
    SpreadsheetCell operator--(int); //Postfix
    
    friend class Spreadsheet;
    //Supply the friend method is not a good idea, it will break the encapsulation.
    friend bool checkSpreadsheetCell(const SpreadsheetCell& cell);
    friend const SpreadsheetCell operator+(const SpreadsheetCell& lhs, const SpreadsheetCell& rhs);
    friend const SpreadsheetCell operator-(const SpreadsheetCell& lhs, const SpreadsheetCell& rhs);
    friend const SpreadsheetCell operator*(const SpreadsheetCell& lhs, const SpreadsheetCell& rhs);
    friend const SpreadsheetCell operator/(const SpreadsheetCell& lhs, const SpreadsheetCell& rhs);
    
    friend bool operator==(const SpreadsheetCell& lhs,const SpreadsheetCell& rhs);
    friend bool operator<(const SpreadsheetCell& lhs, const SpreadsheetCell& rhs);
    friend bool operator>(const SpreadsheetCell& lhs, const SpreadsheetCell& rhs);
    friend bool operator!=(const SpreadsheetCell& lhs, const SpreadsheetCell& rhs);
    friend bool operator<=(const
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值