#include
#include
using namespace std;
Class Vector
{
Private:
Double * v.
int len;
Public:
Friend Vector operator + (Vector& V1, Vector& V2);
Friend Vector operator - (Vector& V1, Vector& V2);
Friend double& The operator * (Vector& V1, Vector& V2);
Friend ostream& Operator<(ostream& Out, Vector& V1);
Friend istream& Operator> (istream& In Vector& V1);
The Vector (int size)//constructor
{
Len=size;
V=new double (len);
}
The Vector (double * v1, int m)//copy structure
{
Len=m;
V=new double (len);
V=v1;
}
//Vector (const Vector& V. v.)
//{
//len=vv. Len;
//v=new double (vv. Len);
//}
~ the Vector ()
{
If (v!=NULL)
{
The delete [] v.
V=NULL;
Len=0;
}
}
Double& Operator [] (int I)
{
If (I & gt;=0 & amp; & I & lt; Len)
Return the v [I];
The else
Cout & lt; <"Overflow!"}
Vector& Operator=(Vector& V1)
{
If (v1. V!=NULL)
{
The delete [] v.
V=new double [v1. Len];
Swap (v, v1. V);
Return * this;
}
}
};
The Vector operator + (Vector& V1, Vector& V2)
{
The Vector temp (v1. Len);
for (int i=0; I & lt; Temp. Len; I++)
{
\ [I]=v1 + v2 [I] [I];
}
//deep copy??
/* delete [] v1. V;
V1. V=new double [v1. Len];
Swap (v1. V, temp. V); */
Return temp.
}
The Vector operator - (Vector& V1, Vector& V2)
{
The Vector temp (v1. Len);
for (int i=0; I & lt; Temp. Len; I++)
{
\ [I]=v1 - v2 [I] [I];
}
Return temp.
}
//)Double& The operator * (Vector& V1, Vector& V2)
{
Double tem=0;
for (int i=0; I & lt; V1. Len; I++)
{
Tem=tem + v1 v2 [I] * [I];
}
Return tem;
}
Ostream& Operator<(ostream& Out, Vector& V1)
{
Cout & lt; <"(";
For (int I=0; I & lt; V1. Len; I++)
{
if (i !=v1. Len - 1)
The out & lt;The else out & lt; }
Return the out;
}
Istream& Operator> (istream& In Vector& V1)
{
for (int i=0; I & lt; V1. Len; I++)
In & gt;> V1 [I];
Return in;
}
Int main ()
{
The Vector v1 (2);
The Vector v2 (2);
Cout & lt; <"Please input the first vector:";
Cin & gt;> V1.
Cout & lt; <"Please input the second vector:";
Cin & gt;> V2.
//call the copy constructor
//Vector v=v1 + v2;
//assignment overloaded function called
The Vector v (2);
V=v1 + v2;
Cout & lt; <"Operation result is:" & lt;}
CodePudding user response:
Your question a lot, such as the parameter of these functions like operator + - */best is const T& Rather than T &, because if it is T& Cannot perform the + - */Opertor=don't swap with it because use the swap will change the original object, the illogical, for example,
Int a=3;
Int b=5;
A=b, a, b should be equal to 5, with swap, b will change
Opertor [] should be a const
Have you put the copy the construct annotation, it is also a problem