一、题目1
分析程序,给出结果。
#include <iostream>
#include <cmath>
using namespace std;
class Magic {
double x; public:
Magic(double d = 0.00) :x(fabs(d)) {}//fabs是cmath头文件的函数,求绝对值的
Magic operator+(const Magic&c) { return Magic(sqrt(x*x + c.x*c.x)); }//sqrt是求平方根
friend ostream& operator<<(ostream & stream, const Magic &c);//函数需要你来实现,输出对象的数据成员值
};
int main()
{
Magic ma;
cout << ma << ", " << Magic(2) << ", " << Magic(-6) + Magic(-8) << endl;//构造函数(实参)——创建无名对象
return 0;
}
(1)请实现<<运算符重载函数(25分)
(2)程序运行结果是___________(25分)
二、题目1解题
(1)
ostream& operator<<(ostream& stream,const Magic& c)
{
stream << c.x;
return stream;//连续输出情况
}
(2)0, 2, 10
三、题目2
有两个矩阵a和b,均为2行3列,求两个矩阵之和。重载运算符“+”使之能用于矩阵直接相加,重载“<<”、">>"运算符,使之能用于该矩阵的输入输出。
提示:矩阵类,可用二维数组(2行3列)作为数据成员。
四、题目2解题
(一)解题思路:
①矩阵类:数据成员有N行M列矩阵,成员函数有重载+函数
②重载流函数为友元函数
③主函数测试
(二)运行结果:
(三)代码
//重载 >> 、 << 、 + , 2 行 3 列矩阵
#include<iostream>
using namespace std;
#define N 2
#define M 3
class matrix//使用系统自动生成的构造函数
{
int mtx[N][M];// N 行 M 列矩阵
public:
friend istream& operator>>(istream&,matrix&);//要修改实参,不加 const ,cin 属于 iostream 类
friend ostream& operator<<(ostream&,const matrix&);//const保护实参对象
matrix& operator+(matrix&);//第一个参数为调用对象,返回对象便主调函数使用,引用减少调用赋值构造函数操作
};
matrix& matrix::operator+(matrix& fmal_mtx)
{
int i,j;
for(i = 0;i < N;++i)
for(j = 0;j < M;++j)
mtx[i][j] += fmal_mtx.mtx[i][j];//加
return *this;
}
istream& operator>>(istream& input,matrix& fmal_mtx)
{
int i,j;// i 行 j 列
for(i = 0;i < N;++i)
for(j = 0;j < M;++j)
input >> fmal_mtx.mtx[i][j];
return input;//连续输入情况
}
ostream& operator<<(ostream& output,const matrix& fmal_mtx)
{
int i,j;// i 行 j 列
for(i = 0;i < N;++i)
{
for(j = 0;j < M;++j) output << fmal_mtx.mtx[i][j] << " ";
output << endl;//界面布局
}
return output;//连续输入情况
}
int main()
{
matrix mtx1,mtx2;
cin >> mtx1 >> mtx2;//cin 是第一个参数
cout << "相加前第一个对象:" << endl << mtx1;
cout << "相加矩阵:" << endl << mtx1 + mtx2;
cout << "相加后第一个对象:" << endl << mtx1;//证明修改后数值在第一个对象
cout << "相加后第二个对象:" << endl << mtx2;//证明第二个对象没有被改变
return 0;
}
(四)总结:
①cin属于istream类,cout属于ostream类,返回istream、ostream形参便连续使用
②>>函数要修改实参对象,不能用const
③+函数返回类对象,方便主调函数使用
④能用引用处用引用,减少不必须的调用赋值构造函数