刚学C++遇到的问题:
重载运算符 输入流>>时, 函数定义的形参必须是实参的引用(别名)
虚函数重写,返回值的类型不能改变(如 int 型不能改为 void 型)
//两个整形数组做+,-,*,运算,参数必须是实参的引用,而且是const型,不然的话,不会报错,但是输出的数据和输入的数据不是一回事,我还没找到原因,也只知道有这么回事
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);
//编码17,运算符重载补充 MyArray2 内联函数方式
#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); //初始化
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;
}