在C++中,類和結(jié)構(gòu)體(struct
)是用于創(chuàng)建類的實(shí)例的藍(lán)圖(或叫模板)。結(jié)構(gòu)體可用于輕量級對象,如矩形,顏色,點(diǎn)等。
與類不同,C++中的結(jié)構(gòu)體(struct
)是值類型而不是引用類型。 如果想在創(chuàng)建結(jié)構(gòu)體之后不想修改的數(shù)據(jù),結(jié)構(gòu)體(struct
)是很有用的。
下面來看看一個(gè)簡單的結(jié)構(gòu)體Rectangle
示例,它有兩個(gè)數(shù)據(jù)成員:width
和height
。
#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