我有一個名爲Fraction的類,我試圖在屏幕上打印它們之前減小分數。我有一個名爲redue()的函數試圖做到這一點,但不知何故,這不管用。下面是我有:
獲取一個錯誤,但不明白爲什麼
// Fraction.cpp
// Implemenation for Fraction header file
//
#include <iostream>
#include <iomanip>
#include "Fraction.h"
#include <stdexcept>
using namespace std;
// Constructor: empty
Fraction:: Fraction(void) {}
// Construcotr: Intializing numerator and denomenator
Fraction:: Fraction(int a, int b)
{
if (b == 0)
{
throw invalid_argument("Error: division by zero");
}
if(b != 0)
{
reduce(a,b);
setNumo(a);
setDeno(b);
}
}
// Overloading operators
ostream &operator<<(ostream &output, const Fraction &fraction)
{
if(fraction.numo == fraction.deno)
{ output<<1;
return output; }
if (fraction.deno == 1)
{ output <<fraction.numo;
return output;}
if((fraction.numo >=0) && (fraction.deno > 0))
{
output <<fraction.numo <<"/"<<fraction.deno;
return output; // prints a/b
}
}
// insertion operator overloading
istream &operator>>(istream &input, Fraction &fraction)
{
int n1,n2;
input >> n1;
input >> fraction.ch;
input >> n2;
Fraction temp(n1, n2);
fraction.numo = temp.numo;
fraction.deno = temp.deno;
return input;
}
// = operator
const Fraction& Fraction::operator=(const Fraction &f)
{
numo = f.numo;
deno = f.deno;
return *this;
}
Fraction Fraction::operator-(const Fraction &fraction) const {
Fraction temp;
int numo1, numo2;
temp.numo = numo * fraction.deno - fraction.numo * deno;
temp.deno = deno * fraction.deno;
Fraction::reduce(temp.numo, temp.deno);
return temp;
}
Fraction Fraction::operator+(const Fraction &fraction) const {
Fraction temp;
temp.numo = numo * fraction.deno + fraction.numo * deno;
temp.deno = deno * fraction.deno;
Fraction::reduce(temp.numo, temp.deno);
return temp;
}
void Fraction:: setNumo(int a)
{ numo = a; }
void Fraction:: setDeno(int b)
{ deno = b; }
static void Fraction::reduce(int &num1, int &num2)
{
int gcd;
gcd = find_gcd(num1, num2);
if(num2 != 0)
{
num1 = num1/gcd;
num2 = num2/gcd;
}
}
int Fraction::find_gcd(int num1, int num2) // returns gcd of two numbers
{
int gcd, remainder;
remainder = num1 % num2;
while(remainder !=0)
{
num1 = num2;
num2 = remainder;
remainder = num1 % num2;
}
gcd = num2;
return gcd;
}
這裏是我的錯誤,當我嘗試編譯該文件:
Fraction.cpp:102:50: error: cannot declare member function ‘static void Fraction::reduce(int&, int&)’ to have static linkage [-fpermissive]
static void Fraction::reduce(int &num1, int &num2)
^
Fraction.cpp: In static member function ‘static void Fraction::reduce(int&, int&)’:
Fraction.cpp:105:30: error: cannot call member function ‘int Fraction::find_gcd(int, int)’ without object
gcd = find_gcd(num1, num2);
有人能告訴我是什麼問題以及如何我可以修復這個問題?我真的需要幫助。先謝謝你。
我真的需要幫助。 – 2014-10-30 06:00:53