C结构体 – 成员函数访问父结构体的变量

huangapple go评论79阅读模式
英文:

C struct - member function accessing variable of parent struct

问题

在C++中,你可以这样做:

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

成员函数可以访问结构体中的其他变量吗?

英文:

In C++ you could do:

class Person{
public:
    int ID;
    char* name;
    void Display(){
        cout &lt;&lt; &quot;Person &quot; &lt;&lt; name &lt;&lt; &quot; ID: &quot; &lt;&lt; ID &lt;&lt; endl;
    }
}

Where the member function can access other variables in a class, is there anyway to do the same with a struct in C?

答案1

得分: 1

以下是您的C++代码的翻译部分:

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

以下是相似的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);
...
英文:

Your C++ code:

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

In C there are no member functions, but similar code in C could look like this:

struct Person {
  int ID;
  char* name;
}

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

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

答案2

得分: 0

C不是一种面向对象的语言,但你可以做类似于这样的事情。

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

typedef void (*DoRunTimeChecks)();

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

void Print(char name[])
{
    printf("打印学生信息\n");
    printf("姓名:%s", name);
}

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

c is not a object oriented language, but you can do something like this.

#include&lt;stdio.h&gt;  
#include &lt;string.h&gt;

typedef void (*DoRunTimeChecks)();

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

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

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

huangapple
  • 本文由 发表于 2020年1月6日 22:39:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/59613986.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定