Just learned about C + + problems:
Overloaded operator input stream >>, the function-defined parameter must be a reference to the argument (alias)
Virtual function overrides, the type of the return value cannot be changed (such as int cannot be changed to void type)
Two array to do +,-,*, operations, parameters must be reference to the argument, and is a const type, otherwise, will not error, but the output of the data and input data is not one thing, I have not found the reason, and only know that
Friend myarray* operator+ (const myarray& M1, const myarray& m2);
Friend myarray* operator+ (const myarray& M1, const int& a);
Friend myarray* operator-(const myarray& M1, const myarray& m2);
Friend Long int operator* (const myarray& M1, const myarray& m2);
Code 17, operator overloading supplemental MyArray2 inline function mode
#include <iostream>
using namespace Std;
Class MyArray
{
Public
MyArray (int length)
{
m_length = length;
M_a = new Int[length];
}
MyArray (int* A, int length)
{
m_length = length;
m_a = new int [length];
for (int i = 0; i < length; i++)
{
M_a[i] = A[i];
}
}
void display ()
{
for (int i = 0; i < m_length; i++)
{
cout<<m_a[i]<< ",";
}
cout<<endl;
}
myarray* operator+ (const myarray& m2);
myarray* operator+ (const int& a);
myarray* operator-(const myarray& m2);
Long int operator* (const myarray& m2);
Private
int* M_a;
int m_length;
};
myarray* myarray::operator+ (const myarray& m2)
{
myarray* C = new MyArray (m_length); Initialization
for (int i = 0; i < m_length; i++)
{
C->m_a[i] = M_a[i] + m2.m_a[i];
}
return C;
}
myarray* myarray::operator+ (const int& a)
{
myarray* C = new MyArray (m_length);
for (int i = 0; i < m_length; i++)
{
C->m_a[i] = M_a[i] + A;
}
return C;
}
myarray* myarray::operator-(const myarray& m2)
{
myarray* C = new MyArray (m_length);
for (int i = 0; i < m_length; i++)
{
C->m_a[i] = M_a[i]-m2.m_a[i];
}
return C;
}
Long int myarray::operator* (const myarray& m2)
{
long int sum = 0;
for (int i = 0; i < m_length; i++)
{
Sum + = m_a[i] * M2.m_a[i];
}
return sum;
}
int main ()
{
int a[] = {4, 7, 8, 9, 10, 32};
MyArray M1 (A, 6);
MyArray m2 (A, 6);
myarray* m3 = m1 + m2 * m2;
myarray* m4 = m1-m2;
Long int r = m1 * m2;
M1.display ();
M2.display ();
M3->display ();
M4->display ();
cout<< "R =" <<r<<endl;
System ("pause");
return 0;
}