3.5对象数组【C++】

1.简介:

对象数组和普通数组没有本质的区别,只不过普通数组的元素是简单变量,而对象数组的元素是对象而已。对象数组在实际中的主要应用在系统需要一个类的多个对象的情况。

例如需要创建100学生档案,每个档案包括姓名,性别,年龄等内容。例如下面:

Student students【100】;

声明了100个学生数组,系统会调用100次,学生类对象的默认构造函数。

【例子3-15】

#include <iostream>
using namespace std;
class Box
{public:
    Box( )  //无参数的构造函数
    {
		length = 1;  width = 1;  height = 1;
        cout << "Box(" << length << ", " << width << ", " << height << ")";
        cout << " is constructed!" << endl;
    }
    Box(float L, float W, float H)  //带有3个形参的构造函数
    {
		length =L;  width = W;   height = H;
        cout << "Box(" << length << ", " << width << ", " << height << ")";
        cout << " is constructed!" << endl;
    }
    float Volume( ){   return length*width*height;   }
    ~Box( )
    {
		cout << "Box(" << length << ", " << width << ", " << height << ")";
        cout << " is destructed!" << endl;
    }
private:
    float length, width, height;
};
int main( )
{
	Box boxs[3];  //创建含有3个元素的对象数组boxs
       //system("pause");
	return 0;
}


【例子3-16】

#include <iostream>
using namespace std;
class Box
{public:
    Box( )                         //无参数的构造函数
    {
        length = 1;  width = 1;  height = 1;
        cout << "Box(" << length << ", " << width << ", " << height << ")";
        cout << " is constructed!" << endl;
    }
    Box(float L, float W, float H)    //带有3个形参的构造函数
    {
       length = L;  width = W;  height = H;
       cout << "Box(" << length << ", " << width << ", " << height << ")";
       cout << " is constructed!" << endl;
    }
    float Volume( ){   return length*width*height;  }
    ~Box( )
    {
        cout << "Box(" << length << ", " << width << ", " << height << ")";
        cout << " is destructed!" << endl;
    }
private:
    float length, width, height;
};
int main( )
{
    Box boxs[3] =

  {
       Box(1, 3, 5),
       Box(2, 4, 6),
       Box(3, 6, 9)
   }; //创建含有3个元素的对象数组并初始化
   //system("pause");
   return 0;
}




发布了36 篇原创文章 · 获赞 17 · 访问量 6274

猜你喜欢

转载自blog.csdn.net/qq_39248307/article/details/78445562
今日推荐