[英]C++ error with operator overloading
我正在嘗試使用運算符重載的程序對有理數進行基本的數學運算。 我一直在函數中遇到錯誤,它說我必須有枚舉類型的算術。 我也得到一個錯誤istream,它表示分子和分母是未定義的。 這是頭文件:
#ifndef rational_H
#define rational_H
#include <iostream>
using namespace std;
class Rational
{
friend ostream & operator<<(ostream & , const Rational &);
friend istream & operator<<(istream & , const Rational &);
public:
// default constructor
Rational(int = 0, int = 1);
// overload operators for "normal" operation
Rational operator+(const Rational&);
Rational operator-(const Rational&);
Rational operator*(const Rational&);
Rational operator/(const Rational&);
operator double();
// overload relational operators for "normal" operation
bool operator>(const Rational&) const;
bool operator<(const Rational&) const;
bool operator>=(const Rational&) const;
bool operator<=(const Rational&) const;
bool operator==(const Rational&) const;
bool operator!=(const Rational&) const;
protected:
int *numerator;
int *denominator;
void reduction(void);
};
#endif
//這部分代碼來自我的理性cpp文件//
// default constructor//
Rational::Rational( int n, int d )
{
*numerator =1 ;
// sets numerator
if(d == 0)
d = 1; // If denominator is zero then set to one.
*denominator = 0;
// sets denominator
reduction(); // store the fraction in reduced form
}
// all the other operators have the same error as well//
Rational Rational::operator-(const Rational&a)
{
Rational sub;
sub.numerator = *this->numerator * a.denominator -//the error is with the 'a'needs to be an arithmetic type or enum type//
*this->denominator * a.numerator;
sub.denominator = *denominator * a.denominator;
sub.reduction();
return sub;
}
//also the istream part has an error where the denominator and numerator is underfined as well//
istream& operator >> ( istream& inputStream, Rational& rnum )
{
inputStream>>rnum.*numerator;//numerator and denmoinator undefined for some reason//
inputStream.ignore(1);
inputStream>>rnum.*denominator;
return inputStream;
}
您的代碼中存在多個小錯誤。 首先,你不應該為這些成員使用指針,它沒有帶來任何好處。
但是,當您選擇這種方式時,每次要讀取或更新它們時都必須取消引用它們,這在operator-
實現中沒有完成,而在operator>>
實現中則不正確(星號需要先放入星號)整個表達)。
您提供的代碼中的下一個錯誤,您在類定義中標記為友元operator<<(istream & , const Rational &)
,但它應該是operator>>
。 並且此聲明需要匹配下一個出現的定義(即,刪除第二個參數的const
,顯然必須進行變異)。
並且,最后但並非最不重要的是,所有解除引用未初始化指針引起的未定義行為......
這可能是復制和過去的錯誤。 這條線
friend istream & operator<<(istream & , const Rational &);
應該
friend istream & operator>>(istream & , Rational &);
稍后您在文件中的實現有:
istream& operator >> ( istream& inputStream, Rational& rnum )
{
...
}
它匹配第二個聲明,而不是第一個聲明。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.