您的位置:首页 > 编程语言 > C语言/C++

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

2016-07-14 13:47 435 查看
刚看到论坛里在讨论题目中的内容,链接:http://bbs.csdn.net/topics/390113751

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

1. c中没有类的概念,所以自然没有构造、析构函数、成员函数,只有数据

而在c++中可以当成类来使用

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中不能被继承

而在c++中可以

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

#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文件

但是函数指针的使用对结构体而言成员不是函数,还是数据成员,类似于int *p。

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

经一同事的提醒,题目也可以理解成c的结构体跟c++的类之间的区别,哈哈
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: