由于C++面向对象的特性,结构体声明与定义相比C语言简化许多。
#include <iostream>
using namespace std;
struct a
{
int a;
void fun()
{
cout << "fun" << endl;
}
};
int main()
{
a stu;//实例化
stu.fun();//调用成员函数
return 0;
}
在C语言中,定义结构体的代码需要使用typedef才能达到相同的效果,并且成员不能为函数,只能是函数指针的形式。
#include <stdio.h>
struct Mode
{
int a;
void (*p)();
};
void fun()
{
printf("I am fun");
}
int main(void)
{
struct Mode a = {1,fun};
//a.p = &fun;
a.p();
return 0;
}