简体   繁体   English

C struct - 访问父结构变量的成员函数

[英]C struct - member function accessing variable of parent struct

In C++ you could do:在 C++ 中,你可以这样做:

class Person{
public:
    int ID;
    char* name;
    void Display(){
        cout << "Person " << name << " ID: " << ID << endl;
    }
}

Where the member function can access other variables in a class, is there anyway to do the same with a struct in C?在成员函数可以访问类中的其他变量的地方,是否可以对 C 中的结构执行相同的操作?

Your C++ code:你的 C++ 代码:

class Person {
public:
    int ID;
    char* name;
    void Display() {
        cout << "Person " << name << " ID: " << ID << endl;
    }
}
...
Person person;
...
person.Display();
...

In C there are no member functions, but similar code in C could look like this:在 C 中没有成员函数,但在 C 中类似的代码可能如下所示:

struct Person {
  int ID;
  char* name;
}

void Display(struct Person *this) {
   printf("Person %s ID: %d\n", this->name, this->ID);
}

...
struct Person person;
...
Display(&Person);
...

c is not a object oriented language, but you can do something like this. c 不是面向对象的语言,但您可以这样做。

#include<stdio.h>  
#include <string.h>

typedef void (*DoRunTimeChecks)();

struct student  
{  
    char name[20];  
    DoRunTimeChecks func;
};  

void Print(char name[])
{
    printf("Printing student information\n");  
    printf("Name: %s",name);  
}

void main ()  
{  
    struct student s = {"shriram", Print}; 
    s.func = Print;
    s.func(s.name);
}  

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

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