在c++中,类和结构体(struct
)是用于创建类的实例的蓝图(或叫模板)。结构体可用于轻量级对象,如矩形,颜色,点等。
与类不同,c++中的结构体(struct
)是值类型而不是引用类型。 如果想在创建结构体之后不想修改的数据,结构体(struct
)是很有用的。
下面来看看一个简单的结构体rectangle
示例,它有两个数据成员: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;
}
上面代码执行得到以下结果 -
area of rectangle is: 40
c++结构示例:使用构造函数和方法
下面来看看另一个结构体的例子,使用构造函数初始化数据和方法来计算矩形的面积。
#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;
}
上面代码执行得到以下结果 -
area of rectangle is: 24