【C++】对象数组

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/CSDN___CSDN/article/details/82954302

运行环境:VS2017

对象数组:每个元素都是同类的对象

如果构造函数只有一个参数,在定义数组时可以直接在等号后面的花括号内提供实参。

Student stud[3]={60,70,80};

如果构造函数有多个参数,则不能用在定义数组时直接提供所有实参的方法,因为一个数组有多个元素,对每个元素要提供多个实参,很容易产生歧义。

编译系统是这样处理的:对于多个参数的类,传入的多个参数分别作为每个元素的第一个实参。

#include<iostream>
using namespace std;
class box
{
public :
	box(int h=10, int w=10, int l=10):height(h),width(w),length(l){}
	int volume();
	~box()//定义析构函数 
	{
		cout << "***" << height<< " " << width  <<" " << length<<  " " <<endl;
	}
private:
	int height;
	int width;
	int length;
};
int box::volume()
{
	return (height*width*length);
}
int main()
{
	box a[4] = {
		box(10,10,10),
		box(10,12,15),
		box(15, 18, 20),
		box(16, 20, 26)
	};
	cout << "The volume of a[0] is " << a[0].volume() << endl;
	cout << "The volume of a[1] is " << a[1].volume() << endl;
	cout << "The volume of a[2] is " << a[2].volume() << endl;
	cout << "The volume of a[3] is " << a[3].volume() << endl;
	return 0;
}

猜你喜欢

转载自blog.csdn.net/CSDN___CSDN/article/details/82954302