默认参数的类型不同

Default parameters are not of the same type?

本文关键字:类型 参数 默认      更新时间:2023-10-16

我之前发布了关于我的构造函数的问题,我以某种方式修复了它。现在,当我尝试使用用户输入声明一个类型为"Rational"的对象而使用默认参数声明另一个对象时,我收到错误。当我尝试使用重载运算符时,它给了我这个错误。

error: no match for 'operator+' (operand types are 'Rational()' and 'Rational')
  Rational xxx = test6+test5;

我。H 文件

#ifndef RATIONAL_H
#define RATIONAL_H
#include <iostream>
#include <stdexcept>
using namespace std;
class Rational {
   private: 
    int num, denom;
   public:
   /* Set Numerator and Denom */
    Rational(int nu, int deno);
    int gcd(int x, int y);
    Rational operator+(const Rational& other);
    Rational operator-(const Rational& other);
    Rational operator*(const Rational& other);
    Rational operator/(const Rational& other);
    friend ostream &operator<<(ostream& os, const Rational& rat);
    void deci();
};
#endif

这是我.cpp文件

#include "Rational2.h"
#include <iostream>
#include <stdexcept>
using namespace std;
int Rational::gcd(int x, int y) {
        while (y != 0) {
             int r(x % y);   // compute remainder
         x = y;
             y = r;
        }
            return x;
}

Rational::Rational(int nu =1, int deno =1){
    if (deno == 0){
        cout << "Denominator Can't Be 0" << endl;   
    }else{
        num =  nu/gcd(nu, deno); 
        denom = deno/gcd(nu, deno);
    }
}
Rational Rational::operator+(const Rational & other){
    int nn = num*other.denom + denom*other.num;
    int dd = denom * other.denom;
    return Rational(nn, dd);
}

测试主文件

Rational test5(3,4)
Rational test6();
Rational xxx = test6+test5;
cout << xxx << endl;

所以它应该正常添加,3/4 + 1/1,如果用户在调用有理类型的对象时不输入任何内容,则 1/1 将是我的默认参数

我不确定是构造函数中的默认参数有问题,还是我的 operator+ 方法不包含添加默认参数的选项?

它应该只处理相同类型的两个对象

更新:

删除括号后,出现此错误

main.cpp:32:11: error: no matching function for call to 'Rational::Rational()'
  Rational test6;
           ^
main.cpp:32:11: note: candidates are:
In file included from main.cpp:2:0:
Rational2.h:13:2: note: Rational::Rational(int, int)
  Rational(int nu, int deno);
  ^
Rational2.h:13:2: note:   candidate expects 2 arguments, 0 provided
Rational2.h:8:7: note: Rational::Rational(const Rational&)
 class Rational {
       ^
Rational2.h:8:7: note:   candidate expects 1 argument, 0 provided

我是否应该创建另一种方法,只是声明 Rational 而我的 cpp 中没有括号?

你的行Rational test6();没有定义一个类型为Rational的新变量,而是定义了一个名为test6的函数,它返回Rational,不带任何参数。要获得所需的行为,请删除括号:Rational test6;

或者,如果您使用的是C++11,我相信您可以使用大括号:Rational test6{};

更新后:您已经告诉我们您的默认参数是 1/1,但您也必须告诉编译器。

您需要将默认值放在现有构造函数上,或者提供默认构造函数。

Rational test6();

信不信由你,但这被解析为名为 test6 () 的函数的声明,该函数返回 Rational 的实例。

从那时起,事情几乎分崩离析。

将其更改为:

Rational test6;

PS:您的操作员过载确实存在一个小问题。它真的应该是:

Rational Rational::operator+(const Rational &other)