用户通常需要创建同一个类的多个对象,这种情况下,可以创建独立对象变量,也可以创建对象数组。
声明对象数组的方法与声明标准类型数组相同。
Student stus[5]; //声明了一个有5个Student对象的数组
注意:要创建类对象数组,则这个类必须有默认构造函数。因为初始化对象数组时,会首先用默认构造函数创建数组元素。
#include "pch.h"
#include "Cuboid.h"
#include <iostream>
using namespace std;
int main()
{
Cuboid c1(20, 10.5, 11.5);
Cuboid c2(11.5, 22, 9.5);
Cuboid cs[2] = {};
cs[0] = Cuboid(20, 10, 11);
cs[1] = Cuboid(1, 4.5, 9);//cs[1](11,26,9);//隐式的无法实现,报错
int res = c1.compare(c2);
res = cs[0].compare(cs[1]);
if (res == 0)
{
cout << "第一个长方体的体积大于第二个长方体的体积" << endl;
}
else if (res == 1)
{
cout << "两个长方体的体积相等" << endl;
}
else
{
cout << "第一个长方体的体积小于第二个长方体的体积" << endl;
}
return 0;
}