个性化阅读
专注于IT技术分析

C结构和C++结构之间有什么区别?

点击下载

本文概述

在C++中, struct和class完全相同, 除了struct默认为公共可见性和class默认为私有可见性。

C和C++结构之间的一些重要区别:

内部成员函数:C中的结构不能在结构内部具有成员函数, 但是C++中的结构可以具有成员函数以及数据成员。

直接初始化:

我们不能直接在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++

//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

使用struct关键字:

在C语言中, 我们需要使用struct声明一个struct变量。在C++中, 没有必要使用struct。例如, 让Record有一个结构。在C语言中, 必须对Record变量使用” struct Record”。在C++中, 我们无需使用struct, 而仅使用” Record”即可。

静态成员:

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++

//C++ program with structure static member
  
struct Record {
     static int x;
};
  
//Driver program
int main()
{
     return 0;
}

这将在C中产生一个错误, 但在C++中不会产生任何错误。

结构中的构造函数创建:C中的结构不能在内部具有构造函数, 但C++中的结构可以具有构造函数创建功能。

C

//C program to demonstrate that Constructor is not allowed
#include <stdio.h>
  
struct Student {
     int roll;
     Student( int x)
     {
         roll = x;
     }
};
  
//Driver Program
int main()
{
     struct Student s(2);
     printf ( "%d" , s.x);
     return 0;
}
/* Output :  Compiler Error
    [Error] expected specifier-qualifier-list 
     before 'Student'
    [Error] expected declaration specifiers or 
    '...' before numeric constant
    [Error] 's' undeclared (first use 
    5555555555in this function)
    In function 'main': */

C++

//CPP program to initialize data member in c++
#include <iostream>
using namespace std;
  
struct Student {
     int roll;
     Student( int x)
     {
         roll = x;
     }
};
  
//Driver Program
int main()
{
     struct Student s(2);
     cout <<s.roll;
     return 0;
}
//Output
//2

输出如下:

2

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

数据隐藏:

C结构不允许隐藏数据的概念, 但C++中允许使用, 因为C++是一种面向对象的语言, 而C语言则不允许。

访问修饰符:

C结构没有访问修饰符, 因为语言不支持这些修饰符。由于C++结构是用语言内置的, 因此可以具有此概念。

相关文章: C++中的结构与类

如果发现任何不正确的地方, 或者想分享有关上述主题的更多信息, 请写评论。

赞(1)
未经允许不得转载:srcmini » C结构和C++结构之间有什么区别?

评论 抢沙发

评论前必须登录!