将类转换为struct

Fre*_*le4 2 c++ parsing code-conversion

我有一个作业,我必须将类似c ++的程序转换为ac程序。

如果我有类似的东西

class B {
    int var;
    int somefunction(){
        some code here
    }
}
Run Code Online (Sandbox Code Playgroud)

它会变成

struct B{
    int var;
}

int somefunction(){
    some code here
}
Run Code Online (Sandbox Code Playgroud)

基本上,我不得不改变class,以struct每次看到它的时候,如果有一个功能,我现在把它移到了外面结构。

做这样的事情的最佳方法是什么?我得到了背后的理论,但不确定如何去实现它。

小智 5

通常,您将指向结构的指针传递给函数。例如,如果您具有以下C ++代码:

class A {
    private:
       int x;
    public:
       A() : x(0) {
       }
       void incx() {
          x++;
       }
};
Run Code Online (Sandbox Code Playgroud)

等效的C代码为:

struct A {
    int x;
};

void init( struct A * a ) {   // replaces constructor
    a->x = 0;
}

void incx( struct A * a ) {
    a->x++;
}
Run Code Online (Sandbox Code Playgroud)

然后这样称呼它:

struct A a;
init( & a );
incx( & a );
Run Code Online (Sandbox Code Playgroud)

但是我不得不问为什么您认为需要将C ++代码转换为C?

  • @Free那将非常非常困难。您将有效地编写以C作为目标语言的C ++编译器。这是第一个C ++编译器(cfront)所做的,但这绝非易事。我认为您可能误解了您的作业。 (2认同)