简体   繁体   English

C将结构作为参数传递(继承)

[英]C Passing structure as argument (inheritance)

Is it possible to do something like this on the C language: 是否可以在C语言上执行以下操作:

class A
{
    public:
        int x;
        int y;
};
class B : public A
{
    public:
        int w;
        int h;
};

void func(A a)
{
    //Do something here
}

int main()
{
    B b;
    func(b);

    return 0;
}

in C with structures? 在C结构? And how should I implement it? 我应该如何实施呢?

Short answer: no. 简短的回答:不。

Longer answer: C is not object oriented, and it will never be object oriented. 更长的答案:C不是面向对象的,它将永远不会是面向对象的。 You can do many object oriented things, like creating structs, and functions that operate on structs. 您可以做许多面向对象的事情,例如创建结构和对结构进行操作的函数。 But if you try to write all your C code by attempting to emulate object oriented standards, you will find it brutal and inefficient. 但是,如果您尝试通过尝试模拟面向对象的标准来编写所有C代码,则会发现它残酷且效率低下。 Inheritance is one of those things that will be brutal and inefficient to implement. 继承是残酷且实现效率低下的事情之一。

However, people frequently use composition instead of inheritance. 但是,人们经常使用合成而不是继承。 This is where you include class A in class B, instead of inheriting. 在这里,您将类A包含在类B中,而不是继承。 If you decide on including parent structs as the first member, you could do this: 如果决定将父结构作为第一个成员,则可以执行以下操作:

struct A { /* stuff */ };
struct B {
  struct A a;
  /* more stuff */
}
void func(void *obj) {
  struct A *a = (struct A *)obj;
  /* do stuff */
}
int main(int argc, char **argv) {
  struct B b;
  func(&b);
}

This is a little scary, and there's no type checking. 这有点吓人,而且没有类型检查。 It will work in many situations, but it won't necessarily have things like polymorphism that you expect from object oriented languages. 它可以在许多情况下工作,但不一定会有您期望的面向对象语言之类的多态性。 Long story short is, try not to rely on object oriented practices -- OOP is just one paradigm, and it's not the only one out there! 长话短说,就是不要依赖于面向对象的实践-OOP只是一种范例,它不是唯一的范例!

Yes, it is possible with struct in C the same way as in C++, ie, by passing objects to the functions. 是的,在C中使用struct的方式与在C ++中实现方式相同,即通过将objects传递给函数。 Suppose the struct is: 假设结构为:

struct A {
           int a;
           int b;
         };

And the function is: 函数是:

void func(A a)
{
//Do something here
}

Then the main() function will be: 然后main()函数将是:

int main()
{
struct A b;
func(b);

return 0;
}

Inheritance is not possible in C. If your aim is to have two structures, one deriving contents from the other, then this may help: 在C语言中无法继承。如果您的目标是拥有两个结构,一个结构从另一个结构派生出内容,那么这可能会有所帮助:

struct A {
           int a;
           int b;
         };

struct B {
           int x;
           int y;
           struct A ob_a;
         };

The function can be modified as: 该函数可以修改为:

void func(B b)
{
//Do something here
}

You can call the function as: 您可以将函数调用为:

struct B ob_b;
func(ob_b);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM