结构体在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. 也有指出函数指针的使用
上面这段代码最好写成.c文件
但是函数指针的使用对结构体而言成员不是函数,还是数据成员,类似于int *p。
以上是根据最上面贴的讨论总结的,欢迎留言。
经一同事的提醒,题目也可以理解成c的结构体跟c++的类之间的区别,哈哈
以前倒也没认真想过这个问题,看了那个帖子后总结了下。
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++的类之间的区别,哈哈
相关文章推荐
- ubuntu升级C++11编写多线程程序
- Reverse Vowels of a String
- 什么是行缓冲?printf输出的条件
- C#和C++的速度大比拼
- C++ 11 中的右值引用
- 《C++编程风格》第二章:一致性
- 《C++ Primer Plus》第14章 C++中的代码重用 学习笔记
- Reverse String
- C语言程序的内存模型
- C++中getline函数
- 258. Add Digits
- NYOJ 521问题
- 在VC++中使用CxImage库读写图像实现像素操作
- 关于弹出消息窗口的自动关闭
- 【C++】深入浅出Win32多线程设计之MFC的多线程
- bd67 c++指针的自我理解
- Leetcode 13. Roman to Integer (Easy) (cpp)
- 338. Counting Bits
- c++全局变量
- 嵌入式C语言实战开发详解(二)