1. 程式人生 > >C++筆記十二:C++對C的擴展——struct關鍵字類型增強

C++筆記十二:C++對C的擴展——struct關鍵字類型增強

wan name undefine char 集合 clu 編程 我們 idt

C語言的struct定義了一組變量的集合,C編譯器並不認為這是一種新的類型。

C++中的struct是一個新類型的定義聲明。

struct Student

{

char name[100];

int age;

};

void main()

{

Student s1={"wang",1};

Student s2={"wang",2};

}

上面程序我們用.c文件,編譯報錯。

這個時候c編譯器不認為Student是一種新的類型,我們必須在Student前面加上struct關鍵字!

struct Student

{

char name[100];

int age;

};

void main()

{

struct Student s1={"wang",1};

struct Student s2={"wang",2};

}

C++對struct關鍵字進行了功能增強。

我們將同樣的在c編譯器下無法編譯的程序放到.cpp文件中,發現是可以編譯通過的!也就是說在C++中認為struct定義了一個新的類型,這個新的類型可以來定義新的變量。

#include<iostream>

using namespace std;

struct Student

{

char name[100];

int age;

};

void main()

{

Student s1={"wang",1};

Student s2={"wang",2};

system("pause");

}

另外呢,C++不單對struct關鍵字進行了類型增強,struct關鍵字和class關鍵字完成的功能是一樣的,當然也有不一樣的地方,區別後面再說。

在結構體裏面也可以加上訪問數據權限:public、protected等。

#include<iostream>

using namespace std;

struct Student

{

public:

char name[100];

int age;

private:

int a;

};

void main()

{

struct Student s1

system("pause");

}

技術分享圖片

技術分享圖片

長按解鎖

解鎖更多精彩內幕

技術分享圖片

依法編程

微信:Lightspeed-Tech

技術驅動生活

C++筆記十二:C++對C的擴展——struct關鍵字類型增強