鍍金池/ 教程/ C++/ C++結(jié)構(gòu)體
C++用戶定義異常
C++ this指針
C++存儲(chǔ)類
C++函數(shù)
C++交換變量值
C++ continue語句
C++注釋
C++函數(shù)遞歸
C++ goto語句
C++函數(shù)-通過值調(diào)用和引用調(diào)用
C++重載
C++語言歷史
C++反轉(zhuǎn)數(shù)字
C++ try/catch語句
C++是什么?
C++變量
C++ break語句
C++運(yùn)算符
C++第一個(gè)程序
C++繼承
C++虛函數(shù)
C++將十進(jìn)制轉(zhuǎn)換為二進(jìn)制
C++矩陣乘法
C++對(duì)象和類
C++基礎(chǔ)輸入輸出(cin,cout,endl)
C++文件和流
C++求素?cái)?shù)
C++ if/else語句
C++友元函數(shù)
C++命名空間
C++面向?qū)ο蟾拍?/span>
C++階乘
C++關(guān)鍵字
C++重載
C++聚合
C++結(jié)構(gòu)體
C++的特點(diǎn)(特性)
C++打印字母表三角
C++ switch語句
C++多態(tài)
C++ do-while循環(huán)
C++字符串
C++ static關(guān)鍵字
C++錯(cuò)誤處理
C++ for循環(huán)
C語言與C++的區(qū)別
C++ while循環(huán)
C++開發(fā)環(huán)境的安裝
linux環(huán)境下編譯C++ 程序
C++枚舉
C++指針
C++斐波納契數(shù)列
C++阿姆斯壯數(shù)字
C++接口
C++教程
C++數(shù)組
C++數(shù)據(jù)抽象
C++回文程序?qū)嵗?/span>
C++打印數(shù)字三角
C++將數(shù)組傳遞到函數(shù)
C++多維數(shù)組
C++將數(shù)字轉(zhuǎn)換字符

C++結(jié)構(gòu)體

在C++中,類和結(jié)構(gòu)體(struct)是用于創(chuàng)建類的實(shí)例的藍(lán)圖(或叫模板)。結(jié)構(gòu)體可用于輕量級(jí)對(duì)象,如矩形,顏色,點(diǎn)等。

與類不同,C++中的結(jié)構(gòu)體(struct)是值類型而不是引用類型。 如果想在創(chuàng)建結(jié)構(gòu)體之后不想修改的數(shù)據(jù),結(jié)構(gòu)體(struct)是很有用的。

C++結(jié)構(gòu)體示例

下面來看看一個(gè)簡單的結(jié)構(gòu)體Rectangle示例,它有兩個(gè)數(shù)據(jù)成員:widthheight。

#include <iostream>  
using namespace std;  
 struct Rectangle    
{    
   int width, height;    

 };    
int main(void) {  
    struct Rectangle rec;  
    rec.width=8;  
    rec.height=5;  
    cout<<"Area of Rectangle is: "<<(rec.width * rec.height)<<endl;  
    return 0;  
}

上面代碼執(zhí)行得到以下結(jié)果 -

Area of Rectangle is: 40

C++結(jié)構(gòu)示例:使用構(gòu)造函數(shù)和方法

下面來看看另一個(gè)結(jié)構(gòu)體的例子,使用構(gòu)造函數(shù)初始化數(shù)據(jù)和方法來計(jì)算矩形的面積。

#include <iostream>  
using namespace std;  
 struct Rectangle    
{    
   int width, height;    
  Rectangle(int w, int h)    
    {    
        width = w;    
        height = h;    
    }    
  void areaOfRectangle() {     
    cout<<"Area of Rectangle is: "<<(width*height); }    
 };    
int main(void) {  
    struct Rectangle rec=Rectangle(4,6);  
    rec.areaOfRectangle();  
    return 0;  
}

上面代碼執(zhí)行得到以下結(jié)果 -

Area of Rectangle is: 24