设为首页 加入收藏

TOP

第1章 关于对象(Object Lessons)(2)
2013-10-07 14:49:11 来源: 作者: 【 】 浏览:58
Tags:关于 对象 Object Lessons

第1章  关于对象(Object Lessons)(2)

更进一步来说,不管哪一种形式,它们都可以被参数化。可以是坐标类型的参数化:

  1. template < class type > 
  2. class Point3d  
  3. {  
  4. public:  
  5.    Point3d( type x = 0.0, type y = 0.0, type z = 0.0 )  
  6.       : _x( x ), _y( y ), _z( z ) { }  
  7.  
  8.    type x() { return _x; }  
  9.    void x( type xval ) { _x = xval; }  
  10.  
  11.    // ... etc ...  
  12. private:  
  13.    type _x;  
  14.    type _y;  
  15.    type _z;  
  16. }; 

也可以是坐标类型和坐标个数两者都参数化:
  1. template < class type, int dim > 
  2. class Point  
  3. {  
  4. public:  
  5.    Point();  
  6.    Point( type coords[ dim ] ) {  
  7.       for ( int index = 0; index < dim; index++ )  
  8.          _coords[ index ] = coords[ index ];  
  9.    }  
  10.  
  11.    type& operator[]( int index ) {  
  12.       assert( index < dim && index >= 0 );  
  13.       return _coords[ index ]; }  
  14.  
  15.    type operator[]( int index ) const  
  16.       {   /* same as non-const instance */   }  
  17.  
  18.    // ... etc ...  
  19. private:  
  20.    type _coords[ dim ];  
  21. };  
  22.  
  23. inline  
  24. template < class type, int dim > 
  25. ostream&  
  26. operator<<( ostream &os, const Point< type, dim > &pt )  
  27. {  
  28.    os << "( ";  
  29.    for ( int ix = 0; ix < dim-1; ix++ )  
  30.       os << pt[ ix ] << ", ";  
  31.    os << pt[ dim-1 ];  
  32.    os << " )";  

很明显,不只在程序风格上有显著的不同,在程序的思考上也有明显的差异。有许多令人信服的讨论告诉我们,从软件工程的眼光来看,为什么"一个ADT或class hierarchy的数据封装"比"在C程序中程序性地使用全局数据"好。但是这些讨论往往被那些"被要求快速让一个应用程序上马应战,并且执行起来又快又有效率"的程序员所忽略。毕竟C的吸引力就在于它的精瘦和简易(相对于C++(www.cppentry.com)而言)。

C++(www.cppentry.com)中实现3D坐标点,比在C中复杂,尤其是使用template的情况下。但这并不意味着C++(www.cppentry.com)就不更有威力,或是(唔,从软件工程的眼光来看)更好。当然啦,更有威力或是更好,也不意味着使用上就更容易。

加上封装后的布局成本(Layout Costs for Adding Encapsulation)

程序员看到Point3d转换到C++(www.cppentry.com)之后,第一个可能会问的问题就是:加上了封装之后,布局成本增加了多少?答案是class Point3d并没有增加成本。三个data members 直接内含在每一个class object之中,就像C struct的情况一样。而member functions虽然含在class的声明之内,却不出现在object之中。每一个non-inline member function只会诞生一个函数实例。至于每一个"拥有零个或一个定义"的inline function则会在其每一个使用者(模块)身上产生一个函数实例。Point3d支持封装性质,这一点并未带给它任何空间或执行期的不良后果。你即将看到,C++(www.cppentry.com)在布局以及存取时间上主要的额外负担是由virtual引起的,包括:

virtual function机制  用以支持一个有效率的"执行期绑定"(runtime binding)。

virtual base class  用以实现"多次出现在继承体系中的base class,有一个单一而被共享的实例"。

此外还有一些多重继承下的额外负担,发生在"一个derived class和其第二或后继之base class的转换"之间。然而,一般而言,并没有什么天生的理由说C++(www.cppentry.com)程序一定比其C兄弟庞大或迟缓。

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇深度探索C++对象模型 推荐 下一篇第1章 关于对象(Object Lessons..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: