将类转换为结构 [英] Converting class to struct
问题描述
我有一个任务,我必须将类似 c++ 的程序转换为 c 程序.
I have an assignment where I have to convert a c++ like program to a c program.
如果我有类似的东西
class B {
int var;
int somefunction(){
some code here
}
}
它会变成
struct B{
int var;
}
int somefunction(){
some code here
}
基本上,我每次看到它时都必须将 class
更改为 struct
,如果有函数,我现在必须将其移出结构体.
Basically, I have to change class
to struct
every time I see it, and if there is a function I have to move it out outside the struct now.
做这样的事情的最佳方法是什么?我明白这背后的理论,但不知道如何去接近它.
What is the best approach to doing something like this? I get the theory behind this but not sure how to go about approaching it.
推荐答案
通常,您将指向结构的指针传递给函数.例如,如果您有以下 C++ 代码:
Typically you pass a pointer to the struct to the function. For example, if you had this C++ code:
class A {
private:
int x;
public:
A() : x(0) {
}
void incx() {
x++;
}
};
等效的 C 代码是:
struct A {
int x;
};
void init( struct A * a ) { // replaces constructor
a->x = 0;
}
void incx( struct A * a ) {
a->x++;
}
然后这样称呼它:
struct A a;
init( & a );
incx( & a );
但我不得不问你为什么认为需要将 C++ 代码转换为 C?
But I have to ask why you think you need to convert C++ code to C?
这篇关于将类转换为结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!