3.30如何用C模仿C++的类

本文探讨了如何在C语言中模仿C++的类特性,通过assert.h进行防御式编程,避免空悬指针等问题。同时,文章提到了C语言中的‘namespace’概念,并介绍如何通过结构体和函数指针实现类似C++的继承和方法。在讨论用C创建类后可能出现的问题时,强调了封装的重要性,并比较了C和C++中设置成员变量的差异,建议遵循Google C++ Style Guide来保持代码规范。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

**

1

**.

assert.h防御式编程
assertion断言

下面所述的在一定情况下为非预期错误的一些例子:

(1)空指针。

(2)输入或者输出参数的值不在预期范围内。

(3)数组的越界。

  assert(date1 == NULL);//进行断言

执行 Assert(1 == 0, “Error”); 结果为:

Assertion failed: 1 == 0

Message: Error


**

2

**

You can have “namespaces” in C (the Apache Portable Runtime prefixes all globals symbols with apr_ and GLib prefixes them with g_ to create a namespace) and other organizing factors without OOP.

“If you need stuff like overloading and/or virtual methods, you probably need to include function pointers in structures”

typedef struct ShapeClass ShapeClass; 
struct  ShapeClass{
   
  float (*computeArea)(const ShapeClass *shape);
} ;

float shape_computeArea(const ShapeClass *shape)
{
   
  return shape->computeArea(shape);
}

This would let you implement a class, by “inheriting” the base class, and implementing a suitable function:


typedef struct {
   
  ShapeClass shape;
  float width, height;
} RectangleClass;

static float rectangle_computeArea(const ShapeClass *shape)
{
   
  const RectangleClass *rect = (const RectangleClass *) shape;
  return rect->width * rect->height;
}
void rectangle_new_with_lengths(RectangleClass *rect, float width, float height)
{
   
  rectangle_new(rect);
  rect
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值