免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 19128 | 回复: 62
打印 上一主题 下一主题

[C++] c与c++区别讨论 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2003-06-21 18:26 |只看该作者 |倒序浏览
讨论这个只是为了以后设计程序时应该怎样思考, 怎样能得到更好更快的设计
欢迎各位发言

从设计模式的角度来讲
c是面向过程的,
c++是面向对象的, 这应该是最主要的区别了

c因为数据与算法分开
所以想用来写面向对象的程序不是很好
我认为

各位发表一下高见

论坛徽章:
0
2 [报告]
发表于 2003-06-21 18:44 |只看该作者

c与c++区别讨论

我觉得c++是对c的一个对象化封装.目的是为了便于软件的大规模生产.

论坛徽章:
0
3 [报告]
发表于 2003-06-21 18:58 |只看该作者

c与c++区别讨论

我觉得C++不是一个C的扩展,而是一门崭新的语言,只是基本的语法和C相同,在C语言世界中,可能可以将
class A
{
public:
int member1,member2;
private:
int  member3;
public:
void Function1();
}


struct A
{
int member1;
int  member2;
int  member3;
}
void A_Function1()
{
}
来代替,但是不可能在C语言世界中实现设计模式中模式,换一句话说,就是不好
在C语言世界中搭建一个好的程序结构(我说的是不好建,但是外国的那些牛人除外)。

论坛徽章:
0
4 [报告]
发表于 2003-06-21 19:07 |只看该作者

c与c++区别讨论

我说的是不好建,但是外国的那些牛人除外



---------foreign strong is too strong to achieve

论坛徽章:
0
5 [报告]
发表于 2003-06-21 19:16 |只看该作者

c与c++区别讨论

先说说两个的概念
如果你使用c++但是不会面向对象那么应该补课了
因为c++的精髓正是支持面向对象


也谈面向对象 //从网上转的,http://www.zdnet.com.cn/developer/tech/story/0,2000081602,39052846,00.htm,更多请看那里

我们经常所说的“对象”,一班指的是解决信息领域内所遇到问题的方法。特别是应用软件技术来解决问题的方法。如我们经常碰到的面向对象的编程(Object-Oriented Programming)、面向对象的分析(Object-Oriented Analysis)、面向对象的设计(Object-Oriented Design)等。应用前面所介绍的关于对象的概念,可以对这些问题做进一步的分析。在面对较复杂的系统,我们可以将它作为一个对象来进行分析。一个系统(解决某个问题的全套解决方案)作为一个对象,可以由多个部分组成。同样,这个对象也可以由多个对象组成。对于同类的事物,可以由一个对象来表示。这样做的益处是显而易见的,它灵活而高效,可以大大减轻设计人员的工作量,简化实际的模型。举一个例子。在关系型数据库的设计当中,我们可以把一个元组当作对象,给它定义一组操作方法。这些方法将适用于所有元组,从而我们不必在更大的范围内去细致的考虑不同的元组(如判断一个元素是否合法):因为它们有一组公共的面向本身的方法,它们“自己”可以“解决”自己的问题。更上一层的对象可以是一个表、视图等。表对象在元组对象的基础上又有它们自己的方法,如增加、删除等。从这个层面上讲,它也只需要做“自己”的事情,因为有元组对象的支持,它无须去考虑像元素是否合法这类的事情。甚至,有时为了满足我们还可以将元素或表群当作时对象并定义它们自己的方法。这样,更能显示面向对象的优势。


面向过程是针对事件发展的过程编程


面向对象是以对象为导向指导设计,c++中的类封装与多态有利于对象的实现
面向过程是以过程为导向指导设计

这是我的理解
各位

论坛徽章:
0
6 [报告]
发表于 2003-06-21 19:22 |只看该作者

c与c++区别讨论

跟大家推荐一个外国牛人写的程序,在
http://www.cs.ucr.edu/~marioh/spatialindex/
非常好,Java式的结构 + C语言的强大

论坛徽章:
0
7 [报告]
发表于 2003-06-21 19:27 |只看该作者

c与c++区别讨论

大家回答的都不错,继续

我觉得C++更适合大软件开发

因为一个复杂系统有很多过程
每个过程又相互关联

如果使用面向过程的话,除非知道整个系统的框架以及需求
不然还是很难定义好接口的
这时可能的做法是把系统分成多个模块, 每个模块是内部紧关联模块间松耦合的
把改动尽量限制在模块内.但如果开始模块分的不好或是需求的改变使系统模块那么代码可能就要重写,这样工作量会很大

但是面向对象则不然
可以把系统分成多个对象,每个对象定义好自己接口, 但是具体实现不定义
这样在需求变化时只要修改某个类自己的实现就可以了
不用全部修改接口
如果需求改变, 改么类还可以重用,类是比模块小的单元, 改运量很小

C因为数据与算法分开
所以想用面向对象的设计,我觉得很难
如果使用C,那么程序的最小单元只能是模块而不可能做到像C++的类

如果有人认为可以在c中使用面向对象
那么请介绍方法,我也想了解一下

论坛徽章:
0
8 [报告]
发表于 2003-06-21 19:56 |只看该作者

c与c++区别讨论

原帖由 "大菠萝" 发表:
我觉得C++不是一个C的扩展,而是一门崭新的语言,只是基本的语法和C相同,在C语言世界中,可能可以将
class A
{
public:
int member1,member2;
private:
int  member3;
public:
void Function1();
}


..........
   

是"封装",连"扩展"都算不上,因为从底层来看,C++没有引入任何新的东西(这也就是C++不如java的原因).
在相当长的一段时间里,C++编译实际上就是先把C++转化成C,然后用C编译器生成代码的.
C++是一个从C时代向OOP时代过渡的一个语言.如果我决定学习OOP,肯定从java甚至Python入手,

论坛徽章:
0
9 [报告]
发表于 2003-06-21 20:01 |只看该作者

c与c++区别讨论

底层的东西不用管

看上层就行了
因为底层都是编译实现的
我们如果想用C实现多态和继承
有了类和多态
就可以认为是OO了

论坛徽章:
0
10 [报告]
发表于 2003-06-21 20:10 |只看该作者

c与c++区别讨论

不要把C++说的这么差,下面是一个线层池的实现,用C++写的,如果你来写,你如何写?

  1. #ifndef THREAD_POOL__HPP
  2. #define THREAD_POOL__HPP

  3. /*  $Id: thread_pool.hpp,v 1.10 2003/02/26 21:34:06 gouriano Exp $
  4. * ===========================================================================
  5. *
  6. *                            PUBLIC DOMAIN NOTICE
  7. *               National Center for Biotechnology Information
  8. *
  9. *  This software/database is a "United States Government Work" under the
  10. *  terms of the United States Copyright Act.  It was written as part of
  11. *  the author's official duties as a United States Government employee and
  12. *  thus cannot be copyrighted.  This software/database is freely available
  13. *  to the public for use. The National Library of Medicine and the U.S.
  14. *  Government have not placed any restriction on its use or reproduction.
  15. *
  16. *  Although all reasonable efforts have been taken to ensure the accuracy
  17. *  and reliability of the software and data, the NLM and the U.S.
  18. *  Government do not and cannot warrant the performance or results that
  19. *  may be obtained by using this software or data. The NLM and the U.S.
  20. *  Government disclaim all warranties, express or implied, including
  21. *  warranties of performance, merchantability or fitness for any particular
  22. *  purpose.
  23. *
  24. *  Please cite the author in any work or product based on this material.
  25. *
  26. * ===========================================================================
  27. *
  28. * Author:  Aaron Ucko
  29. *
  30. * File Description:
  31. *   Pools of generic request-handling threads.
  32. *
  33. *   TEMPLATES:
  34. *      CBlockingQueue<>;  -- queue of requests, with efficiently blocking Get()
  35. *      CThreadInPool<>;   -- abstract request-handling thread
  36. *      CPoolOfThreads<>;  -- abstract pool of threads sharing a request queue
  37. *
  38. *   SPECIALIZATIONS:
  39. *      CStdRequest       -- abstract request type
  40. *      CStdThreadInPool  -- thread handling CStdRequest
  41. *      CStdPoolOfThreads -- pool of threads handling CStdRequest
  42. */

  43. #include <corelib/ncbistd.hpp>;
  44. #include <corelib/ncbithr.hpp>;
  45. #include <corelib/ncbi_limits.hpp>;
  46. #include <util/util_exception.hpp>;

  47. #include <deque>;

  48. BEGIN_NCBI_SCOPE


  49. /////////////////////////////////////////////////////////////////////////////
  50. //
  51. //  TEMPLATES:
  52. //
  53. //     CBlockingQueue<>;  -- queue of requests, with efficiently blocking Get()
  54. //     CThreadInPool<>;   -- abstract request-handling thread
  55. //     CPoolOfThreads<>;  -- abstract pool of threads sharing a request queue
  56. //

  57. template <typename TRequest>;
  58. class CBlockingQueue
  59. {
  60. public:
  61.     CBlockingQueue(unsigned int max_size = kMax_UInt)
  62.         : m_GetSem(0,1), m_PutSem(1,1), m_MaxSize(max_size) {}

  63.     void         Put(const TRequest& data); // Throws exception if full
  64.     void         WaitForRoom(unsigned int timeout_sec  = kMax_UInt,
  65.                              unsigned int timeout_nsec = kMax_UInt) const;
  66.     // Blocks politely if empty
  67.     TRequest     Get(unsigned int timeout_sec  = kMax_UInt,
  68.                      unsigned int timeout_nsec = kMax_UInt);
  69.     unsigned int GetSize(void) const;
  70.     unsigned int GetMaxSize(void) const { return m_MaxSize; }
  71.     bool         IsEmpty(void) const    { return GetSize() == 0; }
  72.     bool         IsFull(void) const     { return GetSize() == GetMaxSize(); }

  73. protected:
  74.     // Derived classes should take care to use these members properly.
  75.     volatile deque<TRequest>; m_Queue;
  76.     CSemaphore               m_GetSem; // Raised iff the queue contains data
  77.     mutable CSemaphore       m_PutSem; // Raised iff the queue has room
  78.     mutable CMutex           m_Mutex;  // Guards access to queue

  79. private:
  80.     unsigned int             m_MaxSize;
  81. };


  82. // Forward declaration
  83. template <typename TRequest>; class CPoolOfThreads;


  84. template <typename TRequest>;
  85. /* abstract */ class CThreadInPool : public CThread
  86. {
  87. public:
  88.     typedef CPoolOfThreads<TRequest>; TPool;

  89.     CThreadInPool(TPool* pool) : m_Pool(pool) {}

  90. protected:
  91.     virtual ~CThreadInPool(void) {}

  92.     virtual void Init(void) {} // called at beginning of Main()

  93.     // Called from Main() for each request this thread handles
  94.     virtual void ProcessRequest(const TRequest& req) = 0;

  95.     virtual void x_OnExit(void) {} // called by OnExit()

  96. private:
  97.     // to prevent overriding; inherited from CThread
  98.     virtual void* Main(void);
  99.     virtual void OnExit(void);

  100.     TPool* m_Pool;
  101. };


  102. template <typename TRequest>;
  103. /* abstract */ class CPoolOfThreads
  104. {
  105. public:
  106.     friend class CThreadInPool<TRequest>;;
  107.     typedef CThreadInPool<TRequest>; TThread;

  108.     CPoolOfThreads(unsigned int max_threads, unsigned int queue_size,
  109.                    int spawn_threshold = 1)
  110.         : m_ThreadCount(0), m_MaxThreads(max_threads),
  111.           m_Delta(0), m_Threshold(spawn_threshold), m_Queue(queue_size)
  112.         {}
  113.     virtual ~CPoolOfThreads(void) {}

  114.     void Spawn(unsigned int num_threads);
  115.     void AcceptRequest(const TRequest& req);
  116.     void WaitForRoom(void)  { m_Queue.WaitForRoom(); }
  117.     bool IsFull(void) const { return m_Queue.IsFull(); }

  118. protected:
  119.     virtual TThread* NewThread(void) = 0;

  120.     volatile unsigned int    m_ThreadCount;
  121.     volatile unsigned int    m_MaxThreads;
  122.     volatile int             m_Delta;     // # unfinished requests - # threads
  123.     int                      m_Threshold; // for delta
  124.     CMutex                   m_Mutex;     // for volatile counters
  125.     CBlockingQueue<TRequest>; m_Queue;
  126. };

  127. /////////////////////////////////////////////////////////////////////////////
  128. //
  129. //  SPECIALIZATIONS:
  130. //
  131. //     CStdRequest       -- abstract request type
  132. //     CStdThreadInPool  -- thread handling CStdRequest
  133. //     CStdPoolOfThreads -- pool of threads handling CStdRequest
  134. //

  135. /* abstract */ class CStdRequest : public CObject
  136. {
  137. public:
  138.     virtual ~CStdRequest(void) {}

  139.     // Called by whichever thread handles this request.
  140.     virtual void Process(void) = 0;
  141. };


  142. class NCBI_XUTIL_EXPORT CStdThreadInPool
  143.     : public CThreadInPool< CRef< CStdRequest >; >;
  144. {
  145. public:
  146.     typedef CThreadInPool< CRef< CStdRequest >; >; TParent;

  147.     CStdThreadInPool(TPool* pool) : TParent(pool) {}

  148. protected:
  149.     virtual void ProcessRequest(const CRef<CStdRequest>;& req)
  150.         { const_cast<CStdRequest&>;(*req).Process(); }

  151.     // virtual void Init(void); // called before processing any requests
  152.     // virtual void x_OnExit(void); // called just before exiting
  153. };


  154. class NCBI_XUTIL_EXPORT CStdPoolOfThreads
  155.     : public CPoolOfThreads< CRef< CStdRequest >; >;
  156. {
  157. public:
  158.     typedef CPoolOfThreads< CRef< CStdRequest >; >; TParent;
  159.     CStdPoolOfThreads(unsigned int max_threads, unsigned int queue_size,
  160.                       int spawn_threshold = 1)
  161.         : TParent(max_threads, queue_size, spawn_threshold) {}

  162.     // void Spawn(unsigned int num_threads);
  163.     // void AcceptRequest(const TRequest& req);

  164.     // Causes all threads in the pool to exit cleanly after finishing
  165.     // all pending requests, optionally waiting for them to die.
  166.     virtual void KillAllThreads(bool wait);

  167. protected:
  168.     virtual TThread* NewThread(void)
  169.         { return new CStdThreadInPool(this); }
  170. };


  171. /////////////////////////////////////////////////////////////////////////////

  172. /////////////////////////////////////////////////////////////////////////////
  173. //  IMPLEMENTATION of INLINE functions
  174. /////////////////////////////////////////////////////////////////////////////


  175. /////////////////////////////////////////////////////////////////////////////
  176. //   CBlockingQueue<>;::
  177. //

  178. template <typename TRequest>;
  179. void CBlockingQueue<TRequest>;::Put(const TRequest& data)
  180. {
  181.     CMutexGuard guard(m_Mutex);
  182.     // Having the mutex, we can safely drop "volatile"
  183.     deque<TRequest>;& q = const_cast<deque<TRequest>;&>;(m_Queue);
  184.     if (q.size() == m_MaxSize) {
  185.         m_PutSem.TryWait();
  186.         NCBI_THROW(CBlockingQueueException, eFull, "CBlockingQueue<>;::Put: "
  187.                    "attempt to insert into a full queue");
  188.     } else if (q.empty()) {
  189.         m_GetSem.Post();
  190.     }
  191.     q.push_back(data);
  192. }


  193. template <typename TRequest>;
  194. void CBlockingQueue<TRequest>;::WaitForRoom(unsigned int timeout_sec,
  195.                                            unsigned int timeout_nsec) const
  196. {
  197.     // Make sure there's room, but don't actually consume anything
  198.     if (m_PutSem.TryWait(timeout_sec, timeout_nsec)) {
  199.         m_PutSem.Post();
  200.     } else {
  201.         NCBI_THROW(CBlockingQueueException, eTimedOut,
  202.                    "CBlockingQueue<>;::WaitForRoom: timed out");        
  203.     }
  204. }


  205. template <typename TRequest>;
  206. TRequest CBlockingQueue<TRequest>;::Get(unsigned int timeout_sec,
  207.                                        unsigned int timeout_nsec)
  208. {
  209.     if ( !m_GetSem.TryWait(timeout_sec, timeout_nsec) ) {
  210.         NCBI_THROW(CBlockingQueueException, eTimedOut,
  211.                    "CBlockingQueue<>;::Get: timed out");        
  212.     }

  213.     CMutexGuard guard(m_Mutex);
  214.     // Having the mutex, we can safely drop "volatile"
  215.     deque<TRequest>;& q = const_cast<deque<TRequest>;&>;(m_Queue);
  216.     TRequest result = q.front();
  217.     q.pop_front();
  218.     if ( ! q.empty() ) {
  219.         m_GetSem.Post();
  220.     }

  221.     // Get the attention of WaitForRoom() or the like; do this
  222.     // regardless of queue size because derived classes may want
  223.     // to insert multiple objects atomically.
  224.     m_PutSem.TryWait();
  225.     m_PutSem.Post();
  226.     return result;
  227. }


  228. template <typename TRequest>;
  229. unsigned int CBlockingQueue<TRequest>;::GetSize(void) const
  230. {
  231.     CMutexGuard guard(m_Mutex);
  232.     return const_cast<const deque<TRequest>;&>;(m_Queue).size();
  233. }


  234. /////////////////////////////////////////////////////////////////////////////
  235. //   CThreadInPool<>;::
  236. //

  237. template <typename TRequest>;
  238. void* CThreadInPool<TRequest>;::Main(void)
  239. {
  240.     Detach();
  241.     Init();

  242.     for (;;) {
  243.         {{
  244.             CMutexGuard guard(m_Pool->;m_Mutex);
  245.             m_Pool->;m_Delta--;
  246.         }}
  247.         ProcessRequest(m_Pool->;m_Queue.Get());
  248.     }

  249.     return 0; // Unreachable, but necessary for WorkShop build
  250. }


  251. template <typename TRequest>;
  252. void CThreadInPool<TRequest>;::OnExit(void)
  253. {
  254.     try {
  255.         x_OnExit();
  256.     } catch (...) {
  257.         // Ignore exceptions; there's nothing useful we can do anyway
  258.     }
  259.     CMutexGuard guard(m_Pool->;m_Mutex);
  260.     m_Pool->;m_ThreadCount--;
  261. }


  262. /////////////////////////////////////////////////////////////////////////////
  263. //   CPoolOfThreads<>;::
  264. //

  265. template <typename TRequest>;
  266. void CPoolOfThreads<TRequest>;::Spawn(unsigned int num_threads)
  267. {
  268.     for (unsigned int i = 0; i < num_threads; i++)
  269.     {
  270.         {{
  271.             CMutexGuard guard(m_Mutex);
  272.             m_ThreadCount++;
  273.         }}
  274.         NewThread()->;Run();
  275.     }
  276. }


  277. template <typename TRequest>;
  278. void CPoolOfThreads<TRequest>;::AcceptRequest(const TRequest& req)
  279. {
  280.     bool new_thread = false;
  281.     {{
  282.         CMutexGuard guard(m_Mutex);
  283.         m_Queue.Put(req);
  284.         if (++m_Delta >;= m_Threshold  &&  m_ThreadCount < m_MaxThreads) {
  285.             // Add another thread to the pool because they're all busy.
  286.             m_ThreadCount++;
  287.             new_thread = true;
  288.         }
  289.     }}

  290.     if (new_thread) {
  291.         NewThread()->;Run();
  292.     }
  293. }

  294. END_NCBI_SCOPE

  295. /*
  296. * ===========================================================================
  297. *
  298. * $Log: thread_pool.hpp,v $
  299. * Revision 1.10  2003/02/26 21:34:06  gouriano
  300. * modify C++ exceptions thrown by this library
  301. *
  302. * Revision 1.9  2002/12/19 14:51:00  dicuccio
  303. * Added export specifier for Win32 DLL builds.
  304. *
  305. * Revision 1.8  2002/11/04 21:29:00  grichenk
  306. * Fixed usage of const CRef<>; and CRef<>; constructor
  307. *
  308. * Revision 1.7  2002/09/13 15:16:03  ucko
  309. * Give CBlockingQueue<>;::{WaitForRoom,Get} optional timeouts (infinite
  310. * by default); change exceptions to use new setup.
  311. *
  312. * Revision 1.6  2002/04/18 15:38:19  ucko
  313. * Use "deque" instead of "queue" -- more general, and less likely to
  314. * yield any name conflicts.
  315. * Make most of CBlockingQueue<>;'s data protected for the benefit of
  316. * derived classes.
  317. * Move CVS log to end.
  318. *
  319. * Revision 1.5  2002/04/11 15:12:52  ucko
  320. * Added GetSize and GetMaxSize methods to CBlockingQueue and rewrote
  321. * Is{Empty,Full} in terms of them.
  322. *
  323. * Revision 1.4  2002/01/25 15:46:06  ucko
  324. * Add more methods needed by new threaded-server code.
  325. * Minor cleanups.
  326. *
  327. * Revision 1.3  2002/01/24 20:17:49  ucko
  328. * Introduce new exception class for full queues
  329. * Allow waiting for a full queue to have room again
  330. *
  331. * Revision 1.2  2002/01/07 20:15:06  ucko
  332. * Fully initialize thread-pool state.
  333. *
  334. * Revision 1.1  2001/12/11 19:54:44  ucko
  335. * Introduce thread pools.
  336. *
  337. * ===========================================================================
  338. */

  339. #endif  /* THREAD_POOL__HPP */
复制代码
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP