第十一章 多态性练习

本文介绍了几个C++编程练习,涉及复数类的加法和减法运算,2行3列矩阵的加减运算及输入输出,人民币类的运算和输入输出,以及时间类的运算和输入输出。此外,还展示了使用弦截法求解多项式方程的示例代码和运行结果。
摘要由CSDN通过智能技术生成

网易云音乐链接 : 点我听歌.

1、定义复数类的加法与减法,使之能够执行下列运算:
complex a(2,5),b(7,8),c(0,0);
c=a+b;
c=4.1+a;
c=b-5.6;

代码

#include <iostream.h>
#include <string.h>

//using namespace std;
class Complex
{
   
	double real;
	double imag;
public:
	Complex() 
	{
   real=0.0; imag=0.0;}
	Complex(double r, double i)
	{
   real = r; imag = i;}
	void show()
	{
   cout<<real<<" + "<<imag<<"i"<<endl;}
	Complex operator+(const Complex &y)				//做为成员函数-对象加法
	{
   
		Complex t(0,0);
		t.real = real + y.real;
		t.imag = imag + y.imag;
		return t;
	}
	Complex operator-(const Complex &y1)				//做为成员函数-对象减法
	{
   
		Complex t(0,0);
		t.real = real - y1.real;
		t.imag = imag - y1.imag;
		return t;
	}
	
	Complex operator+(const double v)
	{
   
		Complex t(0,0);
		t.real = v + real;
		t.imag = imag;
		return t;
	}
	Complex operator-(const double v1)
	{
   
		Complex t(0,0);
		t.real = v1 - real;
		t.imag = -imag;
		return t;
	}

	friend Complex operator-(double, Complex &);
	friend Complex operator+(double, Complex &);
};

Complex operator+(double c1, Complex &c2) 
{
    
	Complex c; 
	c.real=c2.real+c1; 
	c.imag=c2.imag; 
	
	return c; 
} 
Complex operator-(double c1, Complex &c2) 
{
    
 Complex c; 
 c.real=c1-c2.real; 
 c.imag=-c2.imag; 

 return c; 
} 


void main()
{
   
	Complex a(2, 5);Complex b(7, 8);Complex c;
	c = a + b;
	c.show();
	c = 4.1 + a;
	c.show();
	c=b-5.6;
	c.show();
}

运行结果

在这里插入图片描述

◇ 2、设计一个2行3列的矩阵类,重载运算符“+”和“-”,能实现矩阵类对象的加减运算;重载流插入运算符“<<”和流提取运算符“>>”,使之能用于矩阵的输入和输出。

代码

#include <iostream.h>

class matrix
{
   
	private:
		int a[2][3];	
	public:
		friend matrix operator+(matrix&A, matrix&B);
		friend ostream& operator<<(ostream&, matrix&);
		friend istream& operator>>(istream&, matrix&);
		matrix(){
   };
};
 
matrix operator+(matrix&A,matrix&B)
{
   
	matrix c;
	for(int i=0;i<2;i++)
     for(int j=0;j<3;j++)
      c.a[i][j]=A.a[i][j]+B.a[i][j];
	return c;
}
 
istream & operator >> (istream &input,matrix &a)
{
   
    cout<<"请输入矩阵: "<<endl;
  for(int i=0;i<2;i++)
   for(int j=0;j<3;j++)
    input>>a.a[i][j];
  return input;
}
 
ostream & operator << (ostream &output,matrix &C)
{
   
  cout<<"矩阵相加的结果为:"<<endl; 
  for(int i=0;i<2;i++)
  {
   
   for(int j=0;j<3;j++)
    output<<C.a[i][j]<<" ";
   cout<<endl;
	}
  return output;
}
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值