第八周-阅读程序

/* 
 * Copyright (c) 2014, 烟台大学计算机学院 
 * All rights reserved. 
 * 文件名称:test.cpp 
 * 作    者:呼亚萍 
 * 完成日期:2015年4月24日 
 * 版 本 号:v1.0 
 * 
 * 问题描述:运算符的重载
 * 程序输入:相应的程序
 * 程序输出:对应得结果
 */

#include <iostream>
using namespace std;
class Sample
{
public:
    Sample () {}
    Sample(int a)
    {
        x=a;
    }
    void disp()
    {
        cout<<"x="<<x<<endl;
    }
    friend Sample operator+(Sample &s1,Sample &s2);
private:
    int x;
};
Sample operator+(Sample &s1,Sample &s2)
{
    return Sample(s1.x+s2.x);
}
int main()
{
    Sample  obj1(10);
    Sample  obj2(20);
    Sample  obj3;
    obj3=obj1+obj2;
    obj3.disp();
    return 0;
}


运算结果:

#include <iostream>
using namespace std;
class Sample
{
public:
    Sample () {}
    Sample(int a)
    {
        x=a;
    }
    void disp()
    {
        cout<<"x="<<x<<endl;
    }
    Sample operator+(Sample &s1);
private:
    int x;
};
Sample Sample::operator+(Sample &s1)
{
    return Sample(x+s1.x);
}
int main()
{
    Sample  obj1(20);
    Sample  obj2(20);
    Sample  obj3;
    obj3=obj1+obj2;
    obj3.disp();
    return 0;
}


运算结果:

#include <iostream>
using namespace std;
class Wages
{
public:
    Wages(double CBase,double CBonus,double CTax):base(CBase),bonus(CBonus),tax(CTax) {}
    double getpay()const;
    Wages operator+(Wages w)const;
private:
    double base;
    double bonus;
    double tax;
};
double Wages::getpay()const
{
    return base+bonus-tax;
}
Wages Wages::operator+(Wages w)const
{
    return Wages(base+w.base,bonus+w.bonus,tax+w.tax);
}
int main()
{
    Wages w1(2000,500,100),w2(5000,1000,300);
    cout<<(w1+w2).getpay()<<endl;
    return 0;
}


运算结果:

#include<iostream>
using namespace std;
class Pair
{
public:
    Pair(int i,int j):m(i),n(j) {}
    bool operator >(Pair p)const;
private:
    int m;
    int n;
};
bool Pair::operator>(Pair p)const
{
    if(m!=p.m)
        return m>p.m;
    return n>p.n;
}
int main()
{
    Pair p1(3,4),p2(4,3),p3(4,5);
    cout<<(p1>p2)<<(p2>p1)<<(p2>p3)<<(p3>p2);
    return 0;
}


运算结果:

知识点总结:

通过阅读程序,对运算符的重载有了一定的了解,包括成员函数,有元函数。

学习心得:

将实践与书本相结合,使我们对知识点有更加透彻的理解。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值