英文:
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 << "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?
答案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 << "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);
...
答案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<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);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论