2013-04-29 33 views
4

您好我对C++来说比较陌生,在学习一些Java基础知识之后我才开始学习它。 我有预先存在的代码,它已经超载了>>运营商,但是在看了很多教程并试图理解这个问题后,我想我会在这里问。新的C++和重载操作符,不确定如何使用函数

理性CPP文件:

#include "Rational.h" 

#include <iostream> 




Rational::Rational(){ 

} 



Rational::Rational (int n, int d) { 
    n_ = n; 
    d_ = d; 
} 

/** 
* Creates a rational number equivalent to other 
*/ 
Rational::Rational (const Rational& other) { 
    n_ = other.n_; 
    d_ = other.d_; 
} 

/** 
* Makes this equivalent to other 
*/ 
Rational& Rational::operator= (const Rational& other) { 
    n_ = other.n_; 
    d_ = other.d_; 
    return *this; 
} 

/** 
* Insert r into or extract r from stream 
*/ 

std::ostream& operator<< (std::ostream& out, const Rational& r) { 
    return out << r.n_ << '/' << r.d_; 
} 

std::istream& operator>> (std::istream& in, Rational& r) { 
    int n, d; 
    if (in >> n && in.peek() == '/' && in.ignore() && in >> d) { 
     r = Rational(n, d); 
    } 
    return in; 
}} 

Rational.h文件:

#ifndef RATIONAL_H_ 
#define RATIONAL_H_ 

#include <iostream> 
class Rational { 
    public: 

     Rational(); 

     /** 
     * Creates a rational number with the given numerator and denominator 
     */ 
     Rational (int n = 0, int d = 1); 

     /** 
     * Creates a rational number equivalent to other 
     */ 
     Rational (const Rational& other); 

     /** 
     * Makes this equivalent to other 
     */ 
     Rational& operator= (const Rational& other); 

     /** 
     * Insert r into or extract r from stream 
     */ 
     friend std::ostream& operator<< (std::ostream &out, const Rational& r); 
     friend std::istream& operator>> (std::istream &in, Rational& r); 
    private: 
    int n_, d_;}; 

    #endif 

的功能是从一个称为理性预先存在的类,它需要两个int S作为参数。下面是函数重载>>

std::istream& operator>> (std::istream& in, Rational& r) { 
     int n, d; 
     if (in >> n && in.peek() == '/' && in.ignore() && in >> d) { 
      r = Rational(n, d); 
     } 
     return in; 
    } 

而且我尝试使用它这个样子,看到了一些教程后。 (我得到的错误是在"Ambiguous overload for operator>>std::cin>>n1

int main() { 
// create a Rational Object. 
    Rational n1(); 
    cin >> n1; 
} 

就像我说我是新来的这整个重载运营商的事情上,拿捏有人在这里将能够指出我在正确的方向上如何使用此功能。

回答

10

变化Rational n1();Rational n1;。你已经跑进most vexing parseRational n1();不实例化一个Rational对象,但是声明了一个功能名为n1它返回一个Rational对象。

+0

哇!如果它出现在我的代码中,我绝不会追踪它。 – 2013-04-29 19:46:38

+0

@Jesse:很好! – 2013-04-29 19:47:10

+2

@NemanjaBoric,当然可以。这通常与打开编译器警告一样简单。 – chris 2013-04-29 19:47:15

1
// create a Rational Object. 
    Rational n1(); 

这不会产生新的对象,但声明的函数没有参数和返回Rational 你可能是指

// create a Rational Object. 
    Rational n1; 
    cin>>n1;