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

技術驅動生活