c++中的操作符重载,无法调用双参数构造函数

operator overloading in c++ , could not call the two parameter constructor

本文关键字:调用 参数 构造函数 操作符 重载 c++      更新时间:2023-10-16

我的程序要求我在c++中使用操作符重载的概念将两个有理数相加。程序应该读取整行(例如:2/3 + 3/4)并返回结果。程序中的构造函数应该验证有理数(当在分母中输入0时应该显示错误(例如:2/0 + 3/4)。

我写了下面的程序,但是我不能调用我的两个参数构造函数,所以零参数构造函数被执行,并且每次输出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;
 }

下面将简单地构建新的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

对于这个语句,

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;    
}