第1章 关于对象(Object Lessons)(2)
更进一步来说,不管哪一种形式,它们都可以被参数化。可以是坐标类型的参数化:
- template < class type >
- class Point3d
- {
- public:
- Point3d( type x = 0.0, type y = 0.0, type z = 0.0 )
- : _x( x ), _y( y ), _z( z ) { }
-
- type x() { return _x; }
- void x( type xval ) { _x = xval; }
-
- // ... etc ...
- private:
- type _x;
- type _y;
- type _z;
- };
也可以是坐标类型和坐标个数两者都参数化:- template < class type, int dim >
- class Point
- {
- public:
- Point();
- Point( type coords[ dim ] ) {
- for ( int index = 0; index < dim; index++ )
- _coords[ index ] = coords[ index ];
- }
-
- type& operator[]( int index ) {
- assert( index < dim && index >= 0 );
- return _coords[ index ]; }
-
- type operator[]( int index ) const
- { /* same as non-const instance */ }
-
- // ... etc ...
- private:
- type _coords[ dim ];
- };
-
- inline
- template < class type, int dim >
- ostream&
- operator<<( ostream &os, const Point< type, dim > &pt )
- {
- os << "( ";
- for ( int ix = 0; ix < dim-1; ix++ )
- os << pt[ ix ] << ", ";
- os << pt[ dim-1 ];
- 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兄弟庞大或迟缓。