天天看點

初識c++風格的結構體

結構體的建立與使用

 結構體的使用,将多種資料包含在結構體中,結構體可以了解為一個收納盒,将int整型,string字元串型等資料收納進一個struct中,用數學的了解就相當于一個小的集合。

#include<iostream>

#include<string>

using namespace std;

//1建立一個學生的結構體資料類型:有姓名 年齡 分數等

struct  student   //

結構體的建立

{

stringname;

intage;

intscore;

}s3;//s3就是定義的結構體變量名

int main()

//1定義結構體的資料

struct student s1;//結構體:struct student 加變量名:s1

s1.name = "張三";//用變量名加 . 來通路建立的結構體

s1.age= 19;

s1.score= 87;

cout << "姓名:" <<s1.name << "

年齡:" << s1.age << "分數:"<< s1.score << endl;

//2定義結構體直接用

{ 資料 }(順序)

建立資料.

struct student s2 = { "張山",18,85};

cout << "姓名:" <<s2.name << "

年齡:" << s2.age << "分數:"<< s2.score << endl;

//3建立結構體的時候順便定義一下結構體的資料

s3.name = "王波";

s3.age= 22;

s3.score= 99;

cout << "姓名:" <<s3.name << "

年齡:" << s3.age << "分數:"<< s3.score << endl;

}

總結:

文法 struct student s  ----struct結構體類型,student 是結構體标簽,s是該标簽下的變量名

結構體先建立後定義和使用

結構體 在main外建立 在main中定義指派和使用