C++问题(设计并实现一个可由用户在生成对象时给定大小的整数向量类IntVect)

来源:百度知道 编辑:UC知道 时间:2024/06/15 20:51:14
设计并实现一个可由用户在生成对象时给定大小的整数向量类IntVect。
下面是一个使用IntVect类的程序示例及输出结果。

void main ( )
{
IntVect v1(4); // 生成一个含四个分量的向量,即v1=(0, 0, 0, 0)
v1[0] = 1;
v1[1] = 2;
v1[2] = 3;
v1[3] = 4; // 此时v1=(1, 2, 3, 4)
IntVect v2 = v1; // 此时v2=(1, 2, 3, 4)
IntVect v3 = v1 + v2; // 此时v3=(1, 2, 3, 4)
IntVect v4;
v4 = v1 - v2; // 此时v4=(0, 0, 0, 0)
cout << v3 << endl << v4 << endl;
}

上面程序的输出结果应该为:
(2, 4, 6, 8)
(0, 0, 0, 0)
我自已写的半天也不行,,哪位高手发我一个,,

#include<iostream.h>
class CIntVect
{
int *m_len;
int length;
public:
CIntVect()//不带参数的构造函数
{
m_len=NULL;
length=0;
}
~CIntVect()
{
if(m_len!=NULL)
delete m_len;
}
CIntVect(int len);
CIntVect(CIntVect&t);
int &operator[](int x);
CIntVect &operator=(CIntVect&Vect);
CIntVect operator+(CIntVect&Vect);
CIntVect operator-(CIntVect&Vect);
friend ostream& operator<<(ostream &stream,CIntVect&a)//这里写得不是很好,m_string在堆中的内存没释放,希望你自己能改进一下。
{
char *m_string=new char[2*a.length+2];
m_string[0]='(';
m_string[2*a.length]=')';
m_string[2*a.length+1]='\0';
for(int i=1,j=0;i<2*a.length;i++)
{
if(i%2==0)
m_string[i]=',';
else
m_string[i]=char(a.m_len[j++]+'0');
}
stream<<m_string;
return stream;
}<