簡體   English   中英

C struct - 訪問父結構變量的成員函數

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

在 C++ 中,你可以這樣做:

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

在成員函數可以訪問類中的其他變量的地方,是否可以對 C 中的結構執行相同的操作?

你的 C++ 代碼:

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

在 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 不是面向對象的語言,但您可以這樣做。

#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