C++实验: 运算符重载

C++实验: 运算符重载

1.实验目的

(1)进一步了解运算符重载的概念与使用方法。

(2)掌握几种常用的运算符重载方法。

(3)了解转换构造函数的使用方法。

(4)了解在Visual C++6.0环境下进行运算符重载要注意的问题。

2.实验内容

(1)声明一个复数类,重载运算符函数作为其成员函数,使之用于复数计算;

(2)声明一个复数类,重载运算符“+”,使之用于复数加法运算,同时求复数、整数的和;

(3)求已知的矩阵之和,重载运算符“+”,使之用于矩阵相加;

(4)声明一个教师类和学生类,有部分数据成员相同,转换学生对象为教师类,将相同数据移植过去。

3.实验代码

#include <iostream>
using namespace std;

class Complex
{
   
public:
    Complex()
{
    real = 0; imag = 0; }
    Complex(double r, double i) {
    real = r; imag = i; }
    Complex operator + (Complex &c2);
    Complex operator - (Complex &c2);
    Complex operator*(Complex &c2);
    Complex operator/(Complex &c2);
    void display();
private:
    double real;
    double imag;
};

Complex Complex::operator+(Complex &c2)
{
   
    Complex c;
    c.real= real + c2.real;
    c.imag= imag + c2.imag;
    return c;
}

Complex Complex::operator-(Complex &c2)
{
   
    Complex c;
    c.real= real - c2.real;
    c.imag= imag - c2.imag;
    return c;
}

Complex Complex::operator*(Complex &c2)
{
   
    Complex c;
    c.real= real * c2.real -imag * c2.imag;
    c.imag= imag * c2.real +real * c2.imag;
    return c;
}

Complex Complex::operator/(Complex &c2)
{
   
    Complex c;
    c.real= (real*c2.real +imag * c2.imag) /(c2.real*c2.real + c2.imag*c2.imag);
    c.imag= (imag*c2.real -real * c2.imag) /(c2.real*c2.real + c2.imag*c2.imag);
    return c;
}

void Complex::display()
{
   
    cout<<<
  • 4
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

阡陌笙

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值