- Struct 和class 的区别。
【others】struct是一种结构体类型的标志,它和C++中的Class很相似。
C++中两者的唯一区别在于:
l Class定义中默认情况下的成员都是私有的,而结构Struct 定义中默认情况下的成员都是公有的。
l 在C中,结构中不能有成员函数,而在C++中可以有成员函数.
【Jacob】
但struct 中可以有函数指针。
/*编译错误*/
#include <stdio.h>
struct has_memeber_function_s
{
void foo() { printf("has_memeber_function_t:foo()"); };
} ;
typedef struct has_memeber_function_s has_memeber_function_t;
int main()
{
has_memeber_function_t hmf;
hmf.foo();
return 0;
}
// 函数指针
#include <stdio.h>
void foo() { printf("has_memeber_function_t:foo()"); };
struct has_memeber_function_s
{
// Error C can not allow include member function; but can allow function pointer;
//void foo() { printf("has_memeber_function_t:foo()"); };
void(*fun)();
};
typedef struct has_memeber_function_s has_memeber_function_t;
int main()
{
has_memeber_function_t hmf;
hmf.fun = foo;
//hmf.foo();
(*(hmf.fun))();
return 0;
}