真正开始用面向对象思维写程序

来源:互联网 发布:ubuntu下安装emacs 编辑:程序博客网 时间:2024/06/14 04:17

真正开始用面向对象思维写程序

今天,认为自己真正的在用面向对象的思维方式在写程序,其实,也没有那么难,以前都已经实现了的东西,是用结构化的思维完成的,现在把它们整理一个一个的类,关键问题是类和类之间存在着关联,第一步,如何将它们关联起来?这里说的是“整体”和“部分”的关系:

       假设物理世界有一些设备,可能有示波器、频谱仪、三用表等等组成。这里把关键字“设备”、“示波器”各写成一个类,分别是“CInstrument”(设备类)、“COscillograph”(示波器类),各自的C++描述:

  1.     //instrument.h description 设备类描述 
  2.     #pragma once
  3.     #include "oscillograph.h"
  4.     class COscillograph;
  5.     class CInstrument
  6.     {
  7.         public:
  8.             CInstrument();
  9.             
  10.             COscillograph *pOscillograph;       //一个“示波器”对象指针
  11.             //......
  12.             //其他的一些具体仪器
  13.             //………….
  14.     };

       注意上述头文件的第二行,#pragma once是该头文件仅被引用一次,是高版本的用法,低版本可以用:

  1. #ifndef __YOUR_H__
  2. #define __YOUR_H__
  3. //your hpp file
  4. //........
  5. #endif /* __YOUR_H__ */

该类是一个“仪器”类,头文件中用到了“示波器”类,正如第4行所写,先声明它一下。CInstrument(仪器)类中“包含”了一个COscillograph(示波器)的指针,好了,在CInstrument的构造函数中即可一个new一个COscillograph对象了:

  1. CInstrument::CInstrument()
  2. {
  3.     pOscillograph = new COscillograph(this);
  4. }

 

注意: new COscillograph(this)中的this,看到COscillograph的类描述,才明白this的含义。下面是COscillograph(示波器)的描述:

  1.     //oscillograph.h description
  2.     #pragma once
  3.     #include "instrument.h"
  4.     class CInstrument;
  5.     class COscillograph
  6.     {
  7.         public:
  8.             COscillograph(CInstrument *pInstrument);
  9.             
  10.             CInstrument *pInstrument;       //一个“仪器”类指针
  11.             //......
  12.     };

 

可能会看到:instrument.h和oscillograph.h两个头文件互相递归引用,不会出错吗?这也正是#pragma once以及每个类均在互相声明对方是“指针“的原因。看看COscillograph(示波器)类的构造函数,用一个仪器类来初始化它,想干什么?示波器在使用中想使用仪器类中的其他设备,如频谱仪或三用表的某些功能,目的是通过该类中的pInstrument指针,通过它,再得到具体设备的“指针”。好了,看看COscillograph(示波器)构造函数的具体实现吧:

  1. COscillograph::COscillograph(CInstrument *pInstrument)
  2. {
  3.     this->pInstrument = pInstrument;
  4.     //......其他初始化.........
  5. }

上面的this->pInstrument是指的COscillograph类中的pInstrument指针。还记得CInstrument的构造函数吗?里面new一个COscillograph对象时,将CInstrument的指针通过参数传递进来了。

剩下的工作,是在COscillograph或CInstrument类中专心实现各自特定功能了。

 

原创粉丝点击