引言

  C扩展也称C++, 是一个复(za)杂(ji)优(ken)秀(die)的语言. 本文通过开发中常用C++方式
来了解和回顾C++这么语言. C++看了较多的书但还是觉得什么都不会. 只能说自己还付出太少,哎.

在引言部分我们先感受C++类的设计.

有个如下需求, 设计一个简单的日志系统. 先看下面 LogSimple.hpp

  1. #ifndef _HPP_LOGSIMPLE
  2. #define _HPP_LOGSIMPLE
  3.  
  4. #include <iostream>
  5.  
  6. using namespace std;
  7.  
  8. // 特殊技巧构建类构造器
  9. class LogInit {
  10. // 设置LogSimple为友员, 可以访问当前私有属性
  11. friend class LogSimple;
  12.  
  13. // _log写普通文件, _wf写级别高的文件
  14. static FILE* _log;
  15. static FILE* _wf;
  16.  
  17. // 私有的构造器, 证明这个类是私有类
  18. LogInit() {
  19. const char* log = "rpc.log";
  20. const char* wf = "rpc.log.wf";
  21.  
  22. _log = fopen(log, "ab");
  23. if (NULL == _log) {
  24. fprintf(stderr, "fopen is error : %s\n", log);
  25. exit(EXIT_FAILURE);
  26. }
  27.  
  28. _wf = fopen(wf, "ab");
  29. if (NULL == _wf) {
  30. fclose(_log);
  31. fprintf(stderr, "fopen is error : %s\n", wf);
  32. exit(EXIT_FAILURE);
  33. }
  34. }
  35.  
  36. // 析构打开的句柄
  37. ~LogInit() {
  38. fclose(_wf);
  39. fclose(_log);
  40. }
  41. };
  42.  
  43. // 定义静态变量
  44. FILE* LogInit::_log = NULL;
  45. FILE* LogInit::_wf = NULL;
  46.  
  47. // 基础的日志系统
  48. class LogSimple {
  49.  
  50. protected:
  51. // 只能在当前类和继承类中使用的单例对象, 这个只是声明
  52. static LogInit _li;
  53.  
  54. protected:
  55. // 打印普通信息
  56. void LogWrite(string msg) {
  57. fprintf(LogSimple::_li._log, msg.c_str());
  58. }
  59.  
  60. // 打印等级高信息
  61. void WfWrite(string msg) {
  62. fprintf(LogSimple::_li._wf, msg.c_str());
  63. }
  64.  
  65. public:
  66. virtual void Log(string msg) = ;
  67. };
  68.  
  69. // 定义在 LogSimple 中声明的静态量
  70. LogInit LogSimple::_li;
  71.  
  72. // Debug 模式日志
  73. class LogDebug : public LogSimple {
  74.  
  75. public:
  76. // 重写Log输出内容
  77. void Log(string msg) {
  78. #if defined(_DEBUG)
  79. this->LogWrite(msg);
  80. #endif
  81. }
  82. };
  83.  
  84. // Debug 模式日志
  85. class LogFatal : public LogSimple {
  86.  
  87. public:
  88. // 重写Log输出内容
  89. void Log(string msg) {
  90. this->LogWrite(msg);
  91. this->WfWrite(msg);
  92. }
  93. };
  94.  
  95. #endif // !_HPP_LOGSIMPLE

这里使用了 *.hpp 文件,也称C++的充血模型. 当使用 hpp头文件时候表示当前代码是开源的, 头文件和实现都在一起.

并且不使用全局变量和全局函数.

还有这段代码

  1. // 设置LogSimple为友员, 可以访问当前私有属性
  2. friend class LogSimple;
  3.  
  4. ......
  5.  
  6. // 只能在当前类和继承类中使用的单例对象, 这个只是声明
  7. static LogInit _li;

是构建上层语言的 类的构造器. "只会在第一次使用这个类的时候构建这个对象". C++中通过技巧能够完成一切, 是一个强调技巧,强混乱约束的语言.

测试代码如下 main.cpp

  1. #include "LogSimple.hpp"
  2.  
  3. /*
  4. * 主函数, 测试简单的日志系统
  5. * 快速熟悉C++类的使用方法.
  6. */
  7. int main(void) {
  8.  
  9. LogSimple *log;
  10. LogDebug debug;
  11. LogFatal fatal;
  12.  
  13. // 简单测试
  14. log = &debug;
  15. log->Log("debug 日志测试!\n");
  16.  
  17. log = &fatal;
  18. log->Log("fatal 日志测试\n");
  19.  
  20. // 测试完毕
  21. puts("测试完毕!");
  22.  
  23. system("pause");
  24. return ;
  25. }

运行结果

生成日志文件图

再扯一点, C++类中静态变量, 分两步构造,先在类中声明, 再在外面定义分配实际空间. 好,这里关于C++的类回顾完毕.

前言

  前言部分回顾一下C++中模板用法.

开始先回顾了解函数模板, 看下面测试文件 main.cpp

  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5. /*
  6. * 快速排序递归核心, 当前是从小到大排序
  7. */
  8. template <typename T> static void
  9. _sortquick(T a[], int si, int ei) {
  10. // 递归结束条件
  11. if (si >= ei) return;
  12.  
  13. int low = si, high = ei;
  14. T axle = a[low];
  15. while (low < high) {
  16. // 找最右边不合适点
  17. while (low < high && a[high] > axle)
  18. --high;
  19. if (low >= high) break;
  20. a[low++] = a[high];
  21.  
  22. //找最左边不合适点
  23. while (low < high && a[low] < axle)
  24. ++low;
  25. if (low >= high) break;
  26. a[high--] = a[low];
  27. }
  28. // 分界点找好了, 归位 此时low == high
  29. a[low] = axle;
  30.  
  31. //新一轮递归
  32. _sortquick(a, si, low - );
  33. _sortquick(a, high + , ei);
  34. }
  35.  
  36. // 包装对外使用的快排接口
  37. template<typename T> inline void
  38. sortquick(T a[], int len) {
  39. _sortquick(a, , len - );
  40. }
  41.  
  42. /*
  43. * 这里温故函数模板,以快速排序为例
  44. */
  45. int main(void) {
  46. // 开始测试, 模板函数
  47. int a[] = {, , , , , , , , , , };
  48.  
  49. // 开始调用测试 是 sortquick<int> 自动推导
  50. sortquick(a, sizeof(a) / sizeof(*a));
  51.  
  52. puts("排序后数据为:");
  53. for (int i = ; i < sizeof(a) / sizeof(*a); ++i)
  54. printf("%d ", a[i]);
  55. putchar('\n');
  56.  
  57. system("pause");
  58. return ;
  59. }

通过 template<typename T> 构建一个模板的快排函数. 测试结果如下

再来回顾一下 模板类用法 我们构建一个 简单的 智能指针类 AutoPtr.hpp

  1. #ifndef _HPP_AUTOPTR
  2. #define _HPP_AUTOPTR
  3.  
  4. #include <cstring>
  5. #include <cstdlib>
  6.  
  7. /**
  8. *简单的智能指针,支持创建基本类型 基本类型数组
  9. *支持智能管理对象类型,对象数组类型
  10. *不允许赋值构造,复制构造,不允许new创建
  11. */
  12. template<typename T> class AutoPtr {
  13. T *_ptr;
  14. unsigned _len;
  15. AutoPtr<T>(const AutoPtr<T> &autoPtr);
  16. AutoPtr<T> &operator=(const AutoPtr<T> &autoPtr);
  17. void *operator new(unsigned s);
  18.  
  19. public:
  20. AutoPtr(unsigned len = 1U)
  21. {
  22. this->_len = len;
  23. this->_ptr = !len ? NULL : (T*)calloc(len, sizeof(T));
  24. }
  25. ~AutoPtr(void)
  26. {
  27. for (unsigned u = this->_len; u > 0U; --u)
  28. this->_ptr[u - ].~T();//delete的本质
  29. free(this->_ptr);
  30. }
  31.  
  32. inline T& operator*(void) const
  33. {
  34. return *this->_ptr;
  35. }
  36.  
  37. inline T* operator->(void) const
  38. {
  39. return this->_ptr;
  40. }
  41.  
  42. inline T& operator[](unsigned idx) const
  43. {
  44. return this->_ptr[idx];
  45. }
  46.  
  47. inline T* operator+(unsigned idx) const
  48. {
  49. return this->_ptr + idx;
  50. }
  51. //获取智能托管资源的长度,在数组中有用
  52. inline unsigned size(void)
  53. {
  54. return this->_len;
  55. }
  56. };
  57.  
  58. #endif // !_HPP_AUTOPTR

测试代码如下 main.cpp

  1. #include <iostream>
  2. #include "AutoPtr.hpp"
  3.  
  4. using namespace std;
  5.  
  6. struct abx {
  7. int a;
  8. float b;
  9. char *c;
  10. };
  11.  
  12. /*
  13. * 这里将处理 泛型类的使用讲解
  14. * 泛型还是在开发中少用.这里只是初级熟悉篇.
  15. */
  16. int main(void) {
  17.  
  18. // 先使用基础的用法
  19. AutoPtr<int> iptr;
  20.  
  21. *iptr = ;
  22. printf("*iptr = %d\n", *iptr);
  23.  
  24. // 使用 数组类型
  25. AutoPtr<abx> abs();
  26. printf("abs[6].c = %s\n", abs[].c);
  27.  
  28. system("pause");
  29. return ;
  30. }

演示结果

通过上面两个例子, 练习一下基本熟悉泛型语法简易用法了.高级的用法, 那还得春夏秋冬......

正文

  这里简单讲解STL中开发中用到的容器类.使用一些简单例子,方便上手使用.

先看list 链表使用案子

同样通过代码开始 main.cpp, 通过list处理随机业务.

  1. #include <iostream>
  2. #include <cassert>
  3. #include <ctime>
  4. #include <list>
  5.  
  6. using namespace std;
  7.  
  8. /*
  9. * 主函数 - 熟悉STL list 用法
  10. * 业务需求如下:
  11. * 有一堆这样数据
  12. * 标识 权重
  13. * 1 100
  14. * 2 200
  15. * 3 100
  16. * ... ...
  17. * 需要随机出一个数据.
  18. */
  19.  
  20. class RandGoods {
  21. list<int> idxs; //存所有索引的
  22. list<int> weights; //存所有权重的
  23. int sum; //计算总的权重和
  24. public:
  25. RandGoods(void) {
  26. this->sum = ;
  27. // 初始化随机种子
  28. srand((unsigned)time(NULL));
  29. }
  30.  
  31. /*
  32. * 添加数据
  33. */
  34. void Add(int idx, int weidth) {
  35. // 简单检测一下参数
  36. assert(idx>= && weidth > );
  37.  
  38. this->idxs.push_front(idx);
  39. this->weights.push_front(weidth);
  40. this->sum += weidth;
  41. }
  42.  
  43. // 得到一个随机数据
  44. int Get(void) {
  45. int ns = ;
  46. int rd = rand() % sum;
  47. int len = this->weights.size();
  48. list<int>::iterator it = this->idxs.begin();
  49. list<int>::iterator wt = this->weights.begin();
  50.  
  51. while (wt != this->weights.end()) {
  52. ns += *wt;
  53. if (ns > rd)
  54. return *it;
  55. ++it;
  56. ++wt;
  57. }
  58.  
  59. return -;
  60. }
  61.  
  62. // 输出所有数据
  63. void Print(void) {
  64. list<int>::iterator it = this->idxs.begin();
  65. list<int>::iterator wt = this->weights.begin();
  66.  
  67. puts("当前测试数据如下:");
  68. while (wt != this->weights.end()) {
  69. printf("%3d %3d\n", *it, *wt);
  70. ++it;
  71. ++wt;
  72. }
  73. }
  74. };
  75.  
  76. /*
  77. * 温故 list用法, C++ STL 没有上层语言封装的好用
  78. */
  79. int main(void) {
  80. // 随机对象
  81. RandGoods rg;
  82. int len = rand() % + ; // 返回是 [5, 24]
  83.  
  84. //添加数据
  85. for (int i = ; i < len; ++i) {
  86. int weight = rand() % + ;
  87. rg.Add(i, weight);
  88. }
  89.  
  90. // 这里测试 得到数据
  91. rg.Print();
  92.  
  93. // 得到一个数据
  94. int idx = rg.Get();
  95.  
  96. printf("得到随机物品索引:%d\n", idx);
  97.  
  98. system("pause");
  99. return ;
  100. }

对于STL 库有很多功能, 这里就是最简单的使用方式. 工作中需要用到高级的用法, 可以及时查. 关键是有思路.

演示结果

C++ 的list 没有 java和C#的List好用. 差距太大. 或者说STL相比上层语言提供的容器, 显得不那么自然. 估计是C++是开创者,

后面的语言知道坑在那, 简化创新了. 也可以用vector可变数组代替list. 如果在C中直接用语法层提供的可变数组 int max = 10; int a[max];

在栈上声明可变数组就可以了.

再看queue 队列使用方式

关于stl 容器用法都是比较基础例子, 重点能用, 高级的需要看专门介绍的书籍. 关于队列底层库中常用. 和多线程一起配合.

流程很绕, 这里简单写个容易的例子如下main.cpp

  1. #include <iostream>
  2. #include <queue>
  3.  
  4. using namespace std;
  5.  
  6. /*
  7. * 这里使用 queue队列, 简单使用了解
  8. * 最简单的生产后, 直接消耗
  9. */
  10. int main(void) {
  11.  
  12. queue<double> qds;
  13. int i, len = rand() % + ;
  14. double c;
  15. int a, b;
  16.  
  17. puts("生产的数据如下:");
  18. // 先生产 队列是尾巴插, 头出来
  19. for (i = ; i < len; ++i) {
  20. a = rand();
  21. b = rand();
  22. if (a >= b)
  23. c = a + 1.0 * b / a;
  24. else
  25. c = (double)-b - 1.0 * a / b;
  26.  
  27. // 队列中添加数据
  28. printf("%f ", c);
  29. qds.push(c);
  30. }
  31.  
  32. puts("\n释放的数据如下:");
  33. while (!qds.empty()) {
  34. c = qds.front();
  35. printf("%f ", c);
  36.  
  37. qds.pop();
  38. }
  39. putchar('\n');
  40.  
  41. system("pause");
  42. return ;
  43. }

运行截图如下

注意的是C++队列是尾查头出.

后看map 键值对使用例子

先看 main.cpp

  1. #include <iostream>
  2. #include <map>
  3. #include <string>
  4.  
  5. using namespace std;
  6.  
  7. /*
  8. * 这里是使用 map. 简单的熟悉map的使用方法
  9. */
  10. int main(void) {
  11. map<string, string> kvs;
  12. const char* strs[] = { "Sweet", "are", "the", "uses", "of", "adversity",
  13. "Knowledge", "is", "one", "thing", "but", "faith", "is", "another" };
  14.  
  15. // 先添加数据
  16. int i;
  17. pair<map<string, string>::iterator, bool> pit;
  18. for (i = ; i < sizeof(strs) / sizeof(*strs); ++i) {
  19. pit = kvs.insert(pair<string, string>(strs[i - ], strs[i]));
  20. if (!pit.second) {
  21. printf("插入失败<%s,%s>\n", strs[i-], strs[i]);
  22. }
  23. }
  24.  
  25. // 这里开始查找处理
  26. map<string, string>::iterator it = kvs.find("are");
  27. if (it != kvs.end())
  28. printf("找见了 %s => %s\n", it->first.c_str(), it->second.c_str());
  29. else
  30. printf("没有找见 are => NULL\n");
  31.  
  32. // 全局输出
  33. puts("当前的数据内容如下:");
  34. for (it = kvs.begin(); it != kvs.end(); ++it) {
  35. printf("%s => %s\n", it->first.c_str(), it->second.c_str());
  36. }
  37.  
  38. system("pause");
  39. return ;
  40. }

运行结果

到这里基本上C++ 语言中常用的语法规则, 基本都回顾熟悉完毕了. 后面随着开发, 慢慢了解突破. 最快的熟悉手段还是大量看专业书籍和敲代码.

后记

  错误是难免, 这里纯属回顾C++基础语法. 有问题随时交流, 接受任何C++高玩的批评. 拜~~

C扩展 C++回顾到入门的更多相关文章

  1. [.NET] C# 知识回顾 - 事件入门

    C# 知识回顾 - 事件入门 [博主]反骨仔 [原文]http://www.cnblogs.com/liqingwen/p/6057301.html 序 之前通过<C# 知识回顾 - 委托 de ...

  2. 8、web入门回顾/ Http

    1 web入门回顾 web入门 1)web服务软件作用: 把本地资源共享给外部访问 2)tomcat服务器基本操作      : 启动:  %tomcat%/bin/startup.bat 关闭: % ...

  3. [.NET] C# 知识回顾 - Event 事件

    C# 知识回顾 - Event 事件 [博主]反骨仔 [原文]http://www.cnblogs.com/liqingwen/p/6060297.html 序 昨天,通过<C# 知识回顾 - ...

  4. Batch入门教程丨第二章:认识变量相关概念

    在前两期的学习内容中,我们已经了解了Batch入门教程有关的知识和编程方法,如何编写和运行Windows Batch程序,脚本语言的入门方式等,今天我们将继续深入学习Batch入门教程之认识变量相关概 ...

  5. Batch入门教程丨第一章:部署与Hello World!(下)

    在上期分享的内容中,我们已经掌握了基础理论知识,今天我们将继续了解和学习与Windows Batch有关的知识和编程方法,如何编写和运行Windows Batch程序,脚本语言的入门方式等,从而能够更 ...

  6. [C#] C# 基础回顾 - 匿名方法

    C# 基础回顾 - 匿名方法 目录 简介 匿名方法的参数使用范围 委托示例 简介 在 C# 2.0 之前的版本中,我们创建委托的唯一形式 -- 命名方法. 而 C# 2.0 -- 引进了匿名方法,在 ...

  7. [C#] C# 知识回顾 - 你真的懂异常(Exception)吗?

    你真的懂异常(Exception)吗? 目录 异常介绍 异常的特点 怎样使用异常 处理异常的 try-catch-finally 捕获异常的 Catch 块 释放资源的 Finally 块 一.异常介 ...

  8. [C#] C# 知识回顾 - 学会处理异常

    学会处理异常 你可以使用 try 块来对你觉得可能会出现异常的代码进行分区. 其中,与之关联的 catch 块可用于处理任何异常情况. 一个包含代码的 finally 块,无论 try 块中是否在运行 ...

  9. [C#] C# 知识回顾 - 学会使用异常

    学会使用异常 在 C# 中,程序中在运行时出现的错误,会不断在程序中进行传播,这种机制称为“异常”. 异常通常由错误的代码引发,并由能够更正错误的代码进行 catch. 异常可由 .NET 的 CLR ...

随机推荐

  1. opencv基于HSV的肤色分割

    //函数功能:在HSV颜色空间对图像进行肤色模型分割 //输入:src-待处理的图像,imgout-输出图像 //返回值:返回一个iplimgae指针,指向处理后的结果 IplImage* SkinS ...

  2. Flex4/AS3.0自定义VideoPlayer组件皮肤,实现Flash视频播放器

    要求 必备知识 本文要求基本了解 Adobe Flex编程知识. 开发环境 Flash Builder4/Flash Player11 演示地址 演示地址 资料下载   Adobe Flash Pla ...

  3. confluence启动关闭

    cd /opt/atlassian/confluence/bin startup.sh shutdown.sh

  4. 【EF 2】浅谈ADO数据模型生成串(二):数据库连接串分析

    导读:上篇博客中介绍了ADO生成串的前一部分,本篇博客结合报错,接着介绍剩下的部分. 一.代码展示 <span style="font-family:KaiTi_GB2312;font ...

  5. A new start!

    从今天起,开始每天晚上拿出来半个小时到一个小时的时间来总结今天我做的那些事情,有哪些进步,有哪些不足,有哪些心得和笔记. 以前的学习都是每天学完就往脑袋后面一放,导致很多东西当时学会了,但是后面就都想 ...

  6. Cordova V3.0.0中config.xml配置文件的iOS Configuration

    http://www.cnblogs.com/lovecode/articles/3305655.html   轉載這個 <preference> 关于这个标签的可用设置有: Disall ...

  7. Gestures_Article_4_0

    Technical Article Windows Phone 7™ Gestures Compared Lab version: 1.0.0 Last updated: August 25, 201 ...

  8. 添加favicon.ico网站文件

    <link rel="shortcut icon" type="image/x-icon" href="favicon.ico" me ...

  9. PayPal 开发详解(四):买家付款

    1.点击[立即付款] 2.使用[个人账户]登录paypal  Personal测试帐号 3.核对商品信息 4.确认信息无误,点击[立即付款],提示付款成功,跳转到商家设置的URL 5.URL中包含pa ...

  10. git备忘(长久更新)

    一直想了解一下git,正好最近的有一个问题就是,实验室写的代码,怎么同步到自己宿舍的笔记本上面来.最开始想用dropbox,但是用VS的人都知道,工程文件里面会给你生成乱七八糟的很多东西,很占空间,d ...