重温《Inside The C++ Object Model》(1) --关于对象

开发技术 作者: 2024-06-17 09:10:01
C/C++编程风格//1.C风格(结构化程序设计):数据和函数(操作)没有任何关联性typedef struct Point3d{ float x; float y; float z;} Point3d_t;voidPoint3d_print(const Point3d_t *pd

C/C++ 编程风格

//1.C风格(结构化程序设计):数据和函数(操作)没有任何关联性 typedef struct Point3d { float x; float y; float z; } Point3d_t; void Point3d_print(const Point3d_t *pd) { printf("%g,%g,%g ",pd->x,pd->y,pd->z); }

//2.基于对象(Object-Base):提供抽象数据类型(ADT)来支持封装 class Point3d { friend ostream &operator<<(ostream &os,const Point3d &pt); public: Point3d(float x = 0.0,float y = 0.0,float z = 0.0): _x(x),_y(y),_z(z) {} float x() { return _x; } float y() { return _y; } float z() { return _z; } void x(float xval) { _x = xval; } //etc... private: float _x; float _y; float _z; }; inline ostream & operator<<(ostream &os,const Point3d &pt) { return os << "( " << pt._x << "," << pt._y << "," << pt._z << " )"; }

//3.面向对象(Object-Oriented-Model):提供继承和多态 class Point { public: Point(float x = 0.0): _x(x) {} float x() { return _x; } void x(float xValue) { _x = xValue; } protected: float _x; }; class Point2d : public Point { public: Point2d(float x = 0.0,float y = 0.0): Point(x),_y(y) {} float y() { return _y; } void y(float yValue) { _y = yValue; } protected: float _y; }; class Point3d : public Point2d { friend inline ostream & operator<<(ostream &os,const Point3d &pt); public: Point3d(float x = 0.0,float z = 0.0): Point2d(x,y),_z(z) {} float z() { return _z; } void z(float zValue) { _z = zValue; } private: float _z; }; inline ostream & operator<<(ostream &os," << pt._z << " )"; }

//4.面向泛型:提供模板提供类型无关化的编程风格 //示例(1):仅提供类型参数化 template <typename Type> class Point3d { public: Point3d(Type x = 0.0,Type y = 0.0,Type z = 0.0): _x(x),_z(z) {} Type x() { return _x; } Type y() { return _y; } Type z() { return _z; } void x(const Type &xval) { _x = xval; } //etc... private: Type _x; Type _y; Type _z; };

//示例(2):同时提供类型和数目(int dim)参数化 template <typename Type,int dim> class Point { public: Point() {} Point(Type coordes[dim]) { for (int index = 0; index < dim; ++index) { _coordes[index] = coordes[index]; } } const Type &operator[](int index) const { assert(index < dim && index >= 0); return _coordes[index]; } private: Type _coordes[dim]; }; template <typename Type,int dim> inline ostream &operator<<(ostream &os,const Point< Type,dim > &pt) { os << "( "; for (int i = 0; i < dim; ++i) os << pt[i] << ","; os << ")"; return os; } //测试 int array[] = {11,12,333}; Point<int,3> point(array); cout << point << endl; cout << point[2] << endl;

小结:C++加上封装的布局本钱

(1)3个data-member[数据成员]直接内含在每个class-object[对象]当中,犹如C-Struct1样;

(2)Member-function虽然存在于class的声明中, 却不出现在object当中, 每个non-inline member function[非inline的成员函数]只会诞生1个函数实体;

(3)而inline member function会在其每个使用者身上产生1个函数实体.

 

原创声明
本站部分文章基于互联网的整理,我们会把真正“有用/优质”的文章整理提供给各位开发者。本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
本文链接:http://www.jiecseo.com/news/show_28567.html