运算符重载:如何添加和比较两个类“整数”的数据。和“馏分” [英] Operator Overloading: How to add and compare data of two class "Integer" and "Fraction"

查看:158
本文介绍了运算符重载:如何添加和比较两个类“整数”的数据。和“馏分”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个类整数部分和一个抽象类数字。我想要通过重载 + 执行添加操作,还需要检查值的等号使用重载 ==



1。 Add Integer + Integer = Integer



2。添加分数+分数=分数



3。 Add Integer + Fraction = Fraction



我已经能够进行第一和第二操作,但不能添加整数和分数。



以下是代码片段:


  1. Number.h

      #pragma once 
    #include< iostream>
    template< class T>

    class Number
    {
    virtual const T operator +(const T&)= 0;
    virtual void display(std :: ostream&)const = 0;
    virtual bool operator ==(const T& rhs)const = 0;

    };


  2. Integer.h

      #pragma once 
    #includeNumber.h
    #includeFraction.h
    class Integer:public Number< Integer>
    {
    int intValue;

    public:
    void display(std :: ostream&)const;
    int getValue()const;
    void setValue(int);
    Integer(){}
    Integer(int num);
    const整数运算符+(const Integer&);
    virtual〜Integer(){}
    bool operator ==(const Integer&)const;

    };


  3. Integer.cpp

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

    //参数化构造函数
    Integer :: Integer(int num)
    {
    intValue = num;
    }

    //返回整数值

    int Integer :: getValue()const
    {
    return this-> intValue;
    }

    void Integer :: setValue(int x)
    {
    this-> intValue = x;
    }

    //操作符+重载
    const整数Integer :: operator +(const Integer& secondNumber)
    {
    整数temp = this - > intValue + secondNumber.intValue;
    return temp;
    }

    // operator=重载
    void Integer :: display(std :: ostream& stream)const
    {
    stream< < this-> intValue;
    }

    //比较运算符重载
    bool Integer :: operator ==(const Integer& rhs)const
    {
    return this-> intValue == rhs.intValue;
    }


  4. Fraction.h

      #pragma once 
    #includeNumber.h
    #includeInteger.h

    class Fraction: public Number< Fraction>
    {
    整数_numerator;
    Integer _denominator;
    public:
    void display(std :: ostream&)const;
    Fraction()= delete;
    Fraction(const int& const; int int&);
    const Fraction运算符+(const Fraction&);
    int gcdCalculate(int val1,int val2);
    int lcmCalculate(const int val1,const int val2);
    virtual〜Fraction(){}
    bool operator ==(const Fraction& rhs)const;
    };


  5. Fraction.cpp

      #includeFraction.h
    #include< iostream>

    //参数化构造函数
    Fraction :: Fraction(const int& num,const int& den)
    {
    _numerator.setValue
    _denominator.setValue(den);
    }

    //显示分数值
    void Fraction :: display(std :: ostream& stream)const
    {
    if - > _denominator == 0)
    std :: cout<< Undefined:< this-> _numerator.getValue()< /<< this-> _denominator.getValue()< (由零除异常);
    else
    stream<< this-> _numerator.getValue()< /<< this-> _denominator.getValue();
    }

    //+运算符重载
    const Fraction Fraction :: operator +(const Fraction& numberTwo)
    {
    int lcm = lcmCalculate (this-> _denominator.getValue(),numberTwo._denominator.getValue());
    int multiplier1 = 0;
    if(this-> _denominator.getValue())
    multiplier1 = lcm / this-> _denominator.getValue();
    int multiplier2 = 0;
    if(numberTwo._denominator.getValue())
    multiplier2 = lcm / numberTwo._denominator.getValue();
    return Fraction((this-> _numerator.getValue()* multiplier1)+(numberTwo._numerator.getValue()* multiplier2),lcm);
    }


    // LCM计算

    int Fraction :: lcmCalculate(const int val1,const int val2)
    {
    int temp = gcdCalculate(val1,val2);
    return temp? (val1 / temp * val2):0;
    }

    // GCD计算
    int Fraction :: gcdCalculate(int val1,int val2)
    {
    for(;;)
    {
    if(val1 == 0)return val2;
    val2%= val1;
    if(val2 == 0)return val1;
    Val1%= val2;
    }
    }

    //比较运算符重载
    bool Fraction :: operator ==(const Fraction& rhs)const
    {
    整数numCheck = this-> _numerator;
    Integer denCheck = this-> _denominator;
    if(rhs._numerator.getValue())
    numCheck.setValue(numCheck.getValue()/ rhs._numerator.getValue());
    if(rhs._numerator.getValue())
    denCheck.setValue(denCheck.getValue()/ rhs._denominator.getValue());
    if(numCheck == denCheck){
    return true;
    }
    return false;
    }


问题: p>


  1. 我很困惑如何添加Integer + Fraction类。

  2. 我需要创建另一个类 c> $ 中出现 c>。

假设我尝试添加 Integer + Fraction = Fraction Integer类本身然后我将有类似
的例子

  class Integer:public Number< Integer> 
{
const Fraction运算符+(const Fraction&);
}
const Fraction Integer :: operator +(const Fraction& numberTwo)
{
^^我会在这里得到错误
//添加操作
}

请帮助我。

解决方案

对于你的第一个问题,解决方案是不使用成员函数重载,而是创建一个非成员函数重载,例如

 分数运算符+(整数常数和整数,分数常数和分数)
{
//逻辑在这里添加整数和分数
//可能类似...
Fraction f(integer.getValue(),1); // Create fraction
return f + fraction;
}

上面的代码使用 Fraction :: operator + / code>函数添加整数。


I have two classes Integer and Fraction and one abstract class Number. I am suppose to perform addtion operation by overloading + and also I need to check equality of values using overloading of == operator on these classes.

Operations to be performed

1. Add Integer + Integer = Integer

2. Add Fraction + Fraction = Fraction

3. Add Integer + Fraction = Fraction

I have been able to do 1st and 2nd operation but not able to do addition of integer and fraction.

Below is the code snippet:

  1. Number.h

     #pragma once
    #include <iostream>
    template<class T>
    
    class Number
    {
        virtual const T operator+ (const T &) = 0;
        virtual void display(std::ostream &) const = 0;
        virtual bool operator==(const T& rhs) const = 0;
    
    };
    

  2. Integer.h

     #pragma once
     #include "Number.h"
     #include "Fraction.h"
    class Integer : public Number<Integer>
    {
        int intValue;
    
    public:
        void display(std::ostream &) const;
        int getValue() const;
        void setValue(int);
        Integer() {}
        Integer(int num);
        const Integer operator+ (const Integer &);
        virtual ~Integer() {}
        bool operator==(const Integer&) const;
    
    };
    

  3. Integer.cpp

    #include "Integer.h"
    #include "Number.h"
    #include <iostream>
    #include <string>
    
    // parameterized constructor
    Integer::Integer(int num)
    {
        intValue = num;
    }
    
    // return integer value
    
    int Integer::getValue() const
    {
        return this->intValue;
    }
    
    void Integer::setValue(int x)
    {
        this->intValue = x;
    }
    
    // operator "+" overloading
    const Integer Integer::operator+(const Integer &secondNumber)
    {
        Integer  temp = this->intValue + secondNumber.intValue;
        return temp;
    }
    
    // operator "=" overloading 
    void Integer::display(std::ostream& stream) const
    {
        stream << this->intValue;
    }
    
    // comparasion operator overload
    bool Integer::operator==(const Integer& rhs) const
    {
        return this->intValue == rhs.intValue;
    }
    

  4. Fraction.h

     #pragma once
     #include "Number.h"
     #include "Integer.h"
    
     class Fraction : public Number<Fraction>
     {
         Integer _numerator;
         Integer _denominator;
         public:
        void display(std::ostream &) const;
        Fraction() = delete;
        Fraction(const int &, const int &);
        const Fraction operator+ (const Fraction &);
        int gcdCalculate(int  val1, int  val2);
        int lcmCalculate(const int  val1, const int  val2);
        virtual ~Fraction() {}
        bool operator==(const Fraction& rhs) const;
     };
    

  5. Fraction.cpp

    #include "Fraction.h"
    #include <iostream>
    
    // parameterised constructor 
    Fraction::Fraction(const int & num, const int & den)
    {
        _numerator.setValue(num);
        _denominator.setValue(den);
    }
    
    // display the fraction value
    void Fraction::display(std::ostream & stream) const
    {
            if (this->_denominator == 0)
             std::cout << "Undefined: " << this->_numerator.getValue() << "/" << this->_denominator.getValue() << " (Divide By Zero Exception)";
    else
            stream << this->_numerator.getValue() << "/" << this->_denominator.getValue();
    }
    
    // "+" operator overloading
    const Fraction Fraction::operator+(const Fraction &numberTwo)
    {
        int lcm = lcmCalculate(this->_denominator.getValue(), numberTwo._denominator.getValue());
        int multiplier1 = 0;
        if (this->_denominator.getValue())
        multiplier1 = lcm / this->_denominator.getValue();
        int multiplier2 = 0;
        if (numberTwo._denominator.getValue())
            multiplier2 = lcm / numberTwo._denominator.getValue();
        return Fraction((this->_numerator.getValue() * multiplier1) + (numberTwo._numerator.getValue() * multiplier2), lcm);
    }
    
    
     // LCM Calculation
    
    int Fraction::lcmCalculate(const int  val1, const int  val2)
    {
        int temp = gcdCalculate(val1, val2);
        return temp ? (val1 / temp * val2) : 0;
    }
    
    // GCD Calculation
    int Fraction::gcdCalculate(int val1, int  val2)
    {
        for (;;)
        {    
            if (val1 == 0) return val2;
                val2 %= val1;
            if (val2 == 0) return val1;
                val1 %= val2;
        }
    } 
    
    // comparision operator overload 
    bool Fraction::operator==(const Fraction& rhs) const
    {
        Integer numCheck = this->_numerator;
        Integer denCheck = this->_denominator;
        if (rhs._numerator.getValue())
            numCheck.setValue(numCheck.getValue() / rhs._numerator.getValue());
        if (rhs._numerator.getValue())
            denCheck.setValue(denCheck.getValue() / rhs._denominator.getValue());
        if (numCheck == denCheck) {
            return true;
        }
        return false;
    }
    

QUESTION:

  1. I am confused as how to add Integer + Fraction class.
  2. Do I need to create another class which will inherit from Number class.
  3. How to overload oprator+ present in Number Class.

Suppose I try to add Integer + Fraction = Fraction in the Integer class itself then I will have something like Example

class Integer : public Number<Integer>
{
    const Fraction operator+(const Fraction &);
}
    const Fraction Integer::operator+(const Fraction &numberTwo)
{
                                              ^^ I will get error here           
    // Addition opeartion
}

Please help me.

解决方案

For your first question, the solution is to not use member function overloads, but to create a non-member function overload, e.g.

Fraction operator+(Integer const& integer, Fraction const& fraction)
{
    // Logic to add the integer and fraction here
    // Perhaps something like...
    Fraction f(integer.getValue(), 1);  // Create fraction
    return f + fraction;
}

The code above uses the Fraction::operator+ function to add the integer.

这篇关于运算符重载:如何添加和比较两个类“整数”的数据。和“馏分”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆