开发者

Advantages of OOP [duplicate]

This question already has answers here: Closed 12 years ago.

开发者_Go百科Possible Duplicate:

What's the point of OOP?

What are the advantages of using object-orientated programming over function-orientated.

As a trivial example consider:

struct vector_t {
  int x, y, z;
}

void setVector(vector_t *vector, int _x, int _y, it _z) {
  vector->x = _x;
  vector->y = _y;
  vector->z = _z;
}

vector_t addVector(vector_t* vec1, vector_t* vec2) {
  vector_t vec3;
  vec3.x = vec1->x + vec2->x;
  // and so on...
  return vec3;
}

Now, I am not incredibly familiar with object-orientated programming, but the above would translate to OOP as:

class vector_t {
private:
  int x, y, z;
public:
  void set(int _x, int _y, int _z) { ... };
  int getX() { return x; }
  // ...
  void addVector(vector_t *vec) { ... };
  // ...
};

My question is this? What really makes the second code example so prefered over the first in modern programming? What are the advantages and disadvantages?


Your first code snippet is actually an example of a poor man's OO implementation in a non-OO language. You're defining an abstract data type (vector_t) and all the operations allowed on it (setVector, addVector, etc), but you're not encapsulating all the data and operations into a single logical unit (i.e. a class). This can be useful if you want or need to use C instead of C++ but still want to have some of the benefits of OOP.

Since you're already doing OOP in both examples, I think it should be obvious why the second code snippet is better.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜