首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何用C++实现C++虚函数

如何用C++实现C++虚函数
EN

Stack Overflow用户
提问于 2010-06-25 04:20:01
回答 3查看 12.3K关注 0票数 21

C++语言提供了virtual函数。在纯C语言实现的约束下,如何才能达到类似的效果呢?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2010-06-25 04:27:00

here偷来的。

来自C++类

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

可以派生出C代码片段。class A的三个C++成员函数使用行外(独立)代码重写,并按地址收集到一个名为A_functable的结构中。将A的数据成员与函数表组合成一个名为A的C结构。

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));
}

比必要的更详细,但它让人明白了这一点。

票数 33
EN

Stack Overflow用户

发布于 2010-06-25 04:28:46

@GCC...虚函数是在对象的基类中声明的,然后在子类中被“重写”或实现。也就是说,假设你有Vehicle基类,并且你创建了两个子类,Motorcycle和Automobile。基类将声明AddTires()的一个虚函数,然后子类将实现该函数,并且每个子类将以不同的方式实现它。汽车有4个轮子,而摩托车有2个轮子。但是我不能给你C或C++的语法。希望这能有所帮助

票数 1
EN

Stack Overflow用户

发布于 2010-06-25 04:26:44

虚函数是C++面向对象的一个特性,它们指的是依赖于特定对象实例的方法,而不是你当前带着它们的类型。

换句话说:如果您将一个对象实例化为Bar,然后将其强制转换为Foo,则虚方法仍将是它们在实例化时的方法(在Bar中定义),而其他方法将是来自Foo的方法。

虚函数通常是通过vtables的方式实现的(这是为了让您做更多的研究;)。

你可以通过使用结构作为穷人的对象,并将函数指针保存在其中,从而在C中模拟类似的事情。

(更准确地说,非虚函数使得应该从哪个类获取方法变得不明确,但在实践中,我相信C++使用当前类型。)

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/3113583

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档