面向对象程序设计上机练习十二(运算符重载)

本文介绍了一个关于复数类的实现案例,重点在于如何通过重载运算符来完成复数与双精度浮点数之间的加法运算,并通过类型转换运算符实现结果的输出。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

面向对象程序设计上机练习十二(运算符重载)

Time Limit: 1000MS  Memory Limit: 65536KB
Problem Description
处理一个复数与一个double数相加的运算,结果存放在一个double型变量d1中,输出d1的值。定义Complex(复数)类,在成员函数中包含重载类型转换运算符:operator double(){return real;}
Input
输入占两行:
第1行是一个复数的实部和虚部,数据以空格分开。
第2行是一个实数。
Output
输出占一行,复数的实部和实数之和,小数点后保留1位。
Example Input
2.3 5.4
3.4
Example Output
5.7

Hint


#include <iostream>


using namespace std;


class Complex
{
    double real;
    double image;
    public:
        Complex() {real=0;image=0;}
        void Input()
        {
            cin>>real>>image;
        }
        void Input1()
        {
            cin>>real;
        }
        Complex operator +(Complex &a)  //友元函数的函数重载
        {
            Complex c;
            c.real=a.real+real;
            return c;
        }
        void Show()
        {
            cout<<real<<endl;
        }
};
int main()
{
    Complex a,c;
    a.Input();
    Complex b;
    b.Input1();
    c=a+b;
    c.Show();
    return 0;
}



#include<bits/stdc++.h>
using namespace std;

class Complex
{
private:
    double real, imag;
public:
    Complex(double a = 0, double b = 0)
    {
        real = a;
        imag = b;
    }
    Complex operator + (Complex & c)
    {
        Complex x;
        x.real = real + c.real;
        return x;
    }
    void display()
    {
        cout<<real<<endl;
    }
};
int main()
{
    double x, y;
    cin>>x>>y;
    Complex c1(x, y);
    cin>>x;
    Complex c2(x);
    Complex c3;
    c3 = c1 + c2;
    c3.display();
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值