结构体在c和C++中的区别

刚看到论坛里在讨论题目中的内容,连接:http://bbs.csdn.net/topics/390113751c++

之前倒也没认真想过这个问题,看了那个帖子后总结了下。函数

1. c中没有类的概念,因此天然没有构造、析构函数、成员函数,只有数据测试

   而在c++中能够当成类来使用.net

C++ supports a second keyword, struct, that can be used to define class types. The struct keywords is inherited from C.
If we define a class using the class keyword, then any members defined before the first access label are implicitly private; if we use the struct keyword, then those members are public. Whether we define a class using the class keyword or the struct keyword affects only the default initial access level.指针

 2. 在c中不能被继承code

     而在c++中能够继承

3. 也有指出函数指针的使用ci

#include <stdio.h>
//几个用于测试的函数 
int max(int a, int b)
{
	return a > b ? a : b; 
}

int min(int a, int b)
{
	return a < b ? a : b; 
} 

//结构体 
struct func
{
  int (*max)(int, int);//函数指针 
  int (*min)(int, int);
};

typedef struct func func; //添加别名 

void init(func *data)
{
	data->max = max;//初始化函数指针 
	data->min = min; 
} 

int main()
{
	int a, b; 
	func test;
	
	init(&test); //初始化,你能够说它是构造函数 
	
	a = test.max(100, 215);
	b = test.min(64, 42); 
	
	printf("result:\nmax: %d\nmin: %d\n", a, b); 
	return 0; 
}

上面这段代码最好写成.c文件get

可是函数指针的使用对结构体而言成员不是函数,仍是数据成员,相似于int *p。it

以上是根据最上面贴的讨论总结的,欢迎留言。

经一同事的提醒,题目也能够理解成c的结构体跟c++的类之间的区别,哈哈

相关文章
相关标签/搜索