向量1(类和对象)

目录

题目描述

AC代码


题目描述

n个有序数a1,a2,...,an组成的数组称为n维向量。 为n维向量定义CVector类,包含私有数据成员:

int *data;//存储n维向量

int n; //向量维数。

方法有:无参构造函数,设置n=5,data的数据分别为0,1,2,3,4;构造函数,用虚参n1和数组a初始化n和data的数据;输出函数,按格式输出n维向量的值;析构函数。

主函数输入数据,生成CVector对象并调用输出函数测试。

输入

输入n

输入n维向量

输出

分别调用无参和带参构造函数生成2个CVector对象,输出它们的值。

输入样例1

6
10 1 2 3 4 5

输出样例1

0 1 2 3 4
10 1 2 3 4 5

AC代码

#include<iostream>
using namespace std;
class CVector
{
	int * data;
	int n;
	public:
		CVector(){
			data=new int[5];
			for(int i=0;i<5;i++)
			data[i]=i;
			n=5;
		}
		CVector(int n1,int *a){
			n=n1;
			data=new int[n1];
			for(int i=0;i<n1;i++)
			data[i]=a[i];
		}
		void display(){
			int i;
			for(i=0;i<n-1;i++)
			cout<<data[i]<<' ';
			cout<<data[i]<<endl;
		}
		~CVector(){
			if(data)
			delete[] data;
			data=NULL;
		}		
};
int main() {
	int n,i;
	cin>>n;
	int *p=new int [n];
	CVector a;
	a.display();
	for(i=0;i<n;i++)
	cin>>p[i];
	CVector b(n,p);
	b.display();
	if(p)
	delete[] p;
	p=NULL;
}

猜你喜欢

转载自blog.csdn.net/weixin_62264287/article/details/125394070