C语言和C++语言中结构体的区别


(1)C的结构体内不允许有函数存在,C++允许有内部成员函数,且允许该函数是虚函数。所以C的结构体是没有构造函数、析构函数和this指针的。
(2)C的结构体对内部成员变量的访问权限只能是public,而C++允许public、protected、private三种。
(3)C的结构体是不可以继承的,C++的结构体是可以从其他的结构体或者类继承过来的。
(4)在C中定义结构体类型用typedef,如下:
typedef struct Complex

{
    int read;
    int image;
}complex;

则,可以这样定义结构体变量

complex complex1;

但是如果不使用typedef,则必须这样定义

struct Complex complex1;

complex实际上就是struct Complex的别名,另外这里也可以不写Complex(就不能使用struct Complex complex了)

typedef struct
{
    int read;
    int image;
}complex;

但是在C++中,比较简单

struct Complex
{
    int read;
    int image;
};

定义结构体变量时直接使用

Complex complex1;

(5)在c++中使用typedef的话,会造成区别:

struct Complex
{
    int read;
    int image;
}complex;  //这里complex是一个变量

 

typedef struct Complex2
{
    int read;
    int image;
}complex2; //这里complex2是一个结构体类型

 

使用时对于complex可以直接访问 complex.read,但是对于complex2则必须先定义结构体变量complex2 complex2_2,然后才能访问complex2_2.read。

猜你喜欢

转载自blog.csdn.net/qq_21114325/article/details/80867333