默认参数的类型不同?

时间:2016-02-01 00:58:59

标签: c++ parameters

我之前发过关于我的构造函数的问题,我以某种方式修复了它。现在我在尝试声明类型' 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

我是否想创建另一种方法,只是在没有cpp括号的情况下声明Rational?

3 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:1)

Rational test6();

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

从那时起,事情几乎崩溃了。

将其更改为:

Rational test6;

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

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

答案 2 :(得分:0)

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

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