In C++ you could do:
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?
Your C++ code:
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:
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.
#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);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.