我的程序要求我使用運算符重載的概念在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;
}
你是不是要寫'r = rational(x,y);'? – immibis
當我寫上面的代碼,但它沒有解決 –
當你嘗試調用你想要的構造函數時,出現了什麼問題,*完全*? –