1.
class Complex
{
public:
Complex(const int real, const int imag)
:m_real(real), m_imag(imag)
{
}
~Complex()
{
}
friend const Complex operator+(const Complex& c1, const Complex& c2);
friend const Complex operator+(const Complex& c1, const int c2);
friend const Complex operator+(const int c1, const Complex& c2);
friend ostream &operator<<(ostream &of,const Complex &b);
//private:
int m_real;
int m_imag;
};
ostream &operator<<(ostream &os,const Complex &b)
{
os<<b.m_real<<" + "<<b.m_imag<<"i";
return os;
}
const Complex operator+(const Complex& c1, const Complex& c2)
{
Complex res(0, 0);
res.m_real = c1.m_real + c2.m_real;
res.m_imag = c1.m_imag + c2.m_imag;
return res;
}
const Complex operator+(const Complex& c1, const int c2)
{
Complex res(0, 0);
res.m_real = c1.m_real + c2;
res.m_imag = c1.m_imag;
return res;
}
const Complex operator+(const int c1, const Complex& c2)
{
Complex res(0, 0);
res.m_real = c1 + c2.m_imag;
res.m_imag = c2.m_imag;
return res;
}
int main(int argc, char** argv)
{
Complex com1(1,2);
Complex com2(3,4);
int iInt = 5;
Complex com3 = com1 + com2;
Complex com4 = iInt + com1;
cout<<com1<<endl;
cout<<com2<<endl;
cout<<com3<<endl;;
cout<<com4<<endl;
return 0;
}
2.
class Martrix
{
public:
Martrix()
{
}
friend const Martrix operator+(const Martrix& m1, const Martrix& m2);
friend ostream &operator<<(ostream &os,const Martrix &b);
//private:
int m_data[2][3];
};
const Martrix operator+(const Martrix& m1, const Martrix& m2)
{
Martrix m;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 3; j++)
{
m.m_data[i][j] = m1.m_data[i][j] + m2.m_data[i][j];
}
}
return m;
}
ostream &operator<<(ostream &os,const Martrix &m)
{
os<<"martrix:"<<endl;
for (int i = 0; i < 2; i++)
{
os<<"|";
for (int j = 0; j < 3; j++)
{
if (j != 2)
{
os<<m.m_data[i][j]<<" ";
}
else
{
os<<m.m_data[i][j];
}
}
os<<"|"<<endl;
}
return os;
}
int main(int argc, char** argv)
{
Martrix m1, m2;
for(int i = 0; i < 2; i++)
{
for (int j = 0; j < 3; j++)
{
m1.m_data[i][j] = i + 1 +j;
m2.m_data[i][j] = i + 3 +j;
}
}
Martrix m3 = m1 + m2;
cout<<m1<<endl;
cout<<m2<<endl;
cout<<m3<<endl;
return 0;
}
温馨提示:答案为网友推荐,仅供参考