C ++语言提供 virtual 职能。在纯C语言实施的约束中,如何实现类似的效果?

有帮助吗?

解决方案

这里.

从C ++类

class A {
protected:
    int a;
public:
    A() {a = 10;}
    virtual void update() {a++;}
    int access() {update(); return a;}
};

可以得出C代码片段。三个C ++成员函数 class A 使用台外(独立)代码重写,并通过地址收集到一个名称的结构 A_functable. 。数据成员 A 并将函数表与命名的C结构相结合 A.

struct A;

typedef struct {
    void (*A)(struct A*);
    void (*update)(struct A*);
    int (*access)(struct A*);
} A_functable;

typedef struct A{
    int a;
    A_functable *vmt;
} A;

void A_A(A *this);
void A_update(A* this);
int A_access(A* this);

A_functable A_vmt = {A_A, A_update, A_access};

void A_A(A *this) {this->vmt = &A_vmt; this->a = 10;}
void A_update(A* this) {this->a++;}
int A_access(A* this) {this->vmt->update(this); return this->a;}

/*
class B: public A {
public:
    void update() {a--;}
};
*/

struct B;

typedef struct {
    void (*B)(struct B*);
    void (*update)(struct B*);
    int (*access)(struct A*);
} B_functable;

typedef struct B {
    A inherited;
} B;

void B_B(B *this);
void B_update(B* this);

B_functable B_vmt = {B_B, B_update, A_access};

void B_B(B *this) {A_A(this); this->inherited.vmt = &B_vmt; }
void B_update(B* this) {this->inherited.a--;}
int B_access(B* this) {this->inherited.vmt->update(this); return this->inherited.a;}

int main() {
    A x;
    B y;
    A_A(&x);
    B_B(&y);
    printf("%d\n", x.vmt->access(&x));
    printf("%d\n", y.inherited.vmt->access(&y));
}

更详细的是必要的,但要阐明这一点。

其他提示

@GCC ....在对象的基类中声明虚拟函数,然后在子类中“ Overriden”或实现。即,假设您有车辆基课,您创建了两个子类,摩托车和汽车。基类将声明AddTires()的虚拟函数,然后子类将实现此功能,每个子类将以不同的方式实现。一辆汽车有4个轮子,其中摩托车有2。我不能给您C或C ++的语法。希望这可以帮助

虚拟函数是C ++对象方向的功能。他们指的是取决于特定对象实例的方法,而不是您当前随身携带的类型。

换句话说:如果您实例化对象为bar,则将其施放给FOO,虚拟方法仍然是它们处于实例化的方法(在bar中定义),而其他方法将是foo中的方法。

虚拟函数通常是通过VTABLES实现的(这是您进行更多研究;)。

您可以通过将结构用作穷人的对象并保存功能指针来模拟C中的类似内容。

(更正确地,非虚拟函数使该方法的含糊不清,但实际上,我相信C ++使用当前类型。)

这里 是对虚拟函数的描述。

由于C没有继承的概念,因此无法在平原C中实现虚拟功能。

更新:如下所述,可以使用结构和功能指针在直接C中进行类似于虚拟函数的操作。但是,如果您习惯了具有“真”虚拟函数的C ++等语言,则可能会发现C近似值要优雅和难以使用。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top