int * operator+(int array1[MAXARRAY], int array2[MAXARRAY])What happens when you compile this code?
The code for the overloaded operator is the following:
int * operator+(int array1[MAXARRAY], int array2[MAXARRAY])
{
int array3[MAXARRAY];
for (i=0; i<MAXARRAY; i++)
array3[i]=array1[i] + array2[i];
return array3;
}
You will get the following compiler error:
'operator +' must have at least one formal parameter of class type
This is because you may only define overloaded operators for operands
of class type or enumeration type.
Use getvalue and setvalue
myarray operator+(myarray array1, myarray array2) { myarray temparray; for (int i=0; i<MAXARRAY; i++) temparray.setvalue(i, (array1.getvalue(i) + array2.getvalue(i))); return temparray; }
class pwr { double b; int e; double val; public: pwr(double base, int exp); double get_pwr() {return this->val;} }; pwr::pwr(double base, int exp) { this->b=base; this->e=exp; this->val=1; if (exp==0) return; for( ; exp>0; exp--) this->val=this->val * this->b; }
Because, member functions are implicitly passed a this pointer.
This gives them access to the data members of the object that invoked the
member function.
By contrast, functions defined outside of the class, do not have a
this pointer, and therefore need two objects explicitly passed
to them.
This is because your overloaded << operator will also work for file output.
For instance, if you were sending everything to os,
you should be able to include the following lines of code in your
program and have it work:
#include <fstream>
.
.(definition of class myarray)
.
.(definition of ostream& operator<<(ostream& os, myarray array))
.
int main()
{
myarray array1, array2, array3;
ofstream outData; // declares output stream
// binds program variable outData to file "Data.Out"
outData.open("Data.Out");
//INITIALIZE ARRAYS
.
.
//ADD ARRAYS
.
.
outdata << array1 << array2 << array3;
This prints the three arrays to the ostream which, in this case, is to the
"Data.Out" file.
Your deep copy constructor should look like this:
//------------------------------------ //Deep Copy Constructor //copy the values of another "myarray" //------------------------------------ myarray::myarray(myarray const &a) { value = new int[MAXARRAY]; for (int i = 0; i < MAXARRAY; i++) { value[i] = a.value[i]; } }
Your results should look like this - the change is highlighted:
array1 array2 array3 array4
0 3 3 0
1 4 5 5
2 5 7 7
3 6 9 9
4 7 11 11
Notice that setting array4[0] to 0 no longer also affects array3[0].