2015-10-05 115 views
0

我的程序要求我使用運算符重載的概念在C++中添加兩個有理數。程序應讀取整行(例如:2/3 + 3/4)並返回結果。程序中的構造函數應該驗證有理數(當在分母中輸入0時應該顯示一個錯誤)(例如:2/0 + 3/4)運算符在C++中重載,無法調用兩個參數構造函數

我寫了下面的程序,但是我無法打電話給我的兩個參數的構造函數,所以得到執行零參數的構造函數,以及2結果打印每次。任何人都可以請幫我這。

#include<iostream> 
#include <string> 
using namespace std; 

class rational { 
    int numer; 
    int denom; 
    int result; 

public: 

    rational():numer(1),denom(1) {} 

    rational(int a, int b) { 
     if(b==0) { 
      cout<<"Eror Denominator should be greater than zero"; 
      exit(0); 
     } else { 
      numer=a; 
      denom=b; 
     } 
    } 

    int gcd(int a, int b); 

    friend istream& operator>>(istream &input, rational &r) {   
     int x,y; 
     input>>x; 
     input.ignore(1); 
     input>>y; 

     rational(x,y); // here I am not able to call my constructor 
     return input;  
    } 

    rational operator+(rational c2) { 
     rational temp; 
     rational g; 

     temp.numer=(c2.numer*denom)+(numer*c2.denom); 
     temp.denom=c2.denom*denom; 

     result=g.gcd(temp.numer,temp.denom); 
     temp.numer=temp.numer/result; 
     temp.denom=temp.denom/result; 
     return temp; 
    } 

    friend ostream &operator<<(ostream &output, const rational &r) { 
     if(r.denom==1) { 
      output <<r.numer; 
      return output;    
     } else { 
      output <<r.numer<<"/"<<r.denom; 
      return output;  
     } 
    } 
}; 

int rational:: gcd(int a, int b) { 
    int gc=1; 

    for(int i=1;i<=a&&i<=b;i++) { 
      if((a%i==0)&&(b%i==0)) { 
       gc=i; 
      } 
     } 
    return gc; 
} 

int main() { 
    cout.setf(ios::boolalpha); 
    string op; 

    rational r1; 
    rational r2; 


    cin>>r1>>op>>r2; 
    cout<<(r1+r2)<<endl; 
    int i; 
    cin>>i; 
} 
+1

你是不是要寫'r = rational(x,y);'? – immibis

+0

當我寫上面的代碼,但它沒有解決 –

+2

當你嘗試調用你想要的構造函數時,出現了什麼問題,*完全*? –

回答

0

下面將簡單地構建新的rational對象和破壞,它將不會分配您的當前對象

rational(x,y); 

您需要在類的成員分配在重載<<操作

input >> r.numer >> r.denom; 

實際執行驗證,或者你輸入數據,你可以創建單獨的功能,這將在執行任何計算

#include <stdexcept> 

bool rational::validate() const // private member function 
{ 
     return denom == 0 ? false : true ;  
} 

friend istream& operator>>(istream &input, rational &r) 
{   

     input >> r.numer >>r.denom; 

     if(!r.validate()) 
      throw std::runtime_error("Bad Input") ; 
     return input; 

} 
之前調用

您也可以在參數化構造函數中調用此validate。記住第二個構造函數將在調用參數並使用該對象時被調用。

here

+0

我需要調用參數化的構造函數,因爲這是需求,應該在構造函數中指定驗證的邏輯。任何解決方案 –

0

有了這個說法,

rational r1; 

理性的對象R1的默認構造函數被調用。

rational():numer(1),denom(1) 
{ 

} 

和您正在打印:

cout<<(r1+r2)<<endl; 

所以,你的結果是2,因爲默認值設置爲每次1。

這不工作,你期望它的方式:

cin >> r1>> op>> r2; 

你需要重載流運算符>>你的對象(類),然後添加你的邏輯在那裏。

friend istream& operator>>(istream &input, rational &r) 
{ 

    //push the values into object 
     input >> r.numer >>r.denom;  
} 
+0

我需要參數化的構造函數被調用,因爲這是要求,驗證的邏輯應該在構造函數中指定。任何解決方案 –

+0

你想什麼時候叫它? CIN >> R1 >> >>運算R2;或理性的r1 ;; ?? – basav