C与C++结构体的区别

时间:2023-03-10 05:56:23
C与C++结构体的区别

笔者介绍:姜雪伟,IT公司技术合伙人,IT高级讲师,CSDN社区专家,特邀编辑,畅销书作者,已出版书籍:《手把手教你架构3D游戏引擎》电子工业出版社和《Unity3D实战核心技术详解》电子工业出版社等。

CSDN视频网址:http://edu.csdn.net/lecturer/144

不论在面试中还是项目开发中,都会遇到C与C++混用的情况,面对这些我们就要对它们的区别非常熟悉,这样才能在项目中运用自如。在此也是给读者做一个总结,供参考。。。。。

在C ++中,struct和class是完全相同的,除了该struct默认为public 可见,class默认为private不可见。
C和C ++结构之间的一些重要区别:

  1. 结构内的成员函数:C中的结构不能在结构内部具有成员函数,但C ++中的结构可以与成员函数一起使用。
  2. 直接初始化:我们不能直接初始化C中的结构数据成员,但我们可以在C ++中实现。
首先给读者展示的是C语言代码:
// C program to demonstrate that direct
// member initialization is not possible in C
#include<stdio.h>

struct Record
{
   int x = 7;
};

// Driver Program
int main()
{
    struct Record s;
    printf("%d", s.x);
    return 0;
}
/* Output :  Compiler Error
   6:8: error: expected ':', ',', ';', '}' or
  '__attribute__' before '=' token
  int x = 7;
        ^
  In function 'main': */

输出编译错误,因为在C语言中的成员不能赋初值。


再给读者展示C++中的代码展示:
// CPP program to initialize data member in c++
#include<iostream>
using namespace std;

struct Record
{
    int x = 7;
};

//  Driver Program
int main()
{
    Record s;
    cout << s.x << endl;
    return 0;
}
// Output
// 7

输出结果是7,编译正确。

3、使用struct关键字:在C中,我们需要使用struct声明一个struct变量。在C ++中,struct不是必需的。例如,让Record有一个结构。
在C中,我们必须对Record变量使用“struct Record”。在C ++中,我们不需要使用struct,只能使用'Record'。
4、静态成员: C结构不能有静态成员,但允许使用C ++。
C的案例代码如下所示:
// C program with structure static member
struct Record
{
    static int x;
};

// Driver program
int main()
{
    return 0;
}
/* 6:5: error: expected specifier-qualifier-list
   before 'static'
     static int x;
     ^*/

编译错误,在C中的结构体中不能声明static静态变量。

再看看C++中的代码:
// C++ program with structure static member

struct Record
{
    static int x;
};

// Driver program
int main()
{
    return 0;
}

5、sizeof运算符:该运算符将为C中的空结构生成0,而在C ++中为空结构生成1。

// C program to illustrate empty structure
#include<stdio.h>

//empty structure
struct Record
{
};

//Driver program
int main()
{
    struct Record s;
    printf("%d\n",sizeof(s));
    return 0;
}

输出C:

0

C ++输出:

1

最后两条:

6、数据隐藏: C结构不允许数据隐藏的概念,但在C ++中允许,因为C ++是面向对象的语言,而C不是。
7、访问修饰符: C结构没有访问修饰符,因为这些修饰符不被语言支配。C ++结构可以具有这个概念,因为它在语言中是内置的。