C可以有对象吗

Can C have objects?

本文关键字:对象      更新时间:2023-10-16

我知道C++作为一种编程语言的主要优势之一是它可以支持OOP。

示例:

#include <iostream>
using namespace std;
class CRectangle {
    int x, y;
  public:
    void set_values (int,int);
    int area () {return (x*y);}
};
void CRectangle::set_values (int a, int b) {
  x = a;
  y = b;
}
int main () {
  CRectangle rect;
  rect.set_values (3,4);
  cout << "area: " << rect.area();
  return 0;
}

我想知道C是否也支持OOP,如果是,它是如何实现的。

通常,您只需使用structs并传递上下文指针。直接转换你的例子:

#include <stdio.h>
struct rectangle {
    int x, y;
};
void rectangle_set_values (struct rectangle * rectangle, int a, int b) {
  rectangle->x = a;
  rectangle->y = b;
}
int rectangle_area (struct rectangle * rectangle) {
  return rectangle->x * rectangle->y;
}
int main () {
  struct rectangle rect;
  rectangle_set_values(&rect, 3, 4);
  printf("area: %d", rectangle_area(&rect));
  return 0;
}