c ++和重载运算符的新手,不确定如何使用该函数

时间:2013-04-29 19:40:34

标签: c++ operators overloading

您好我是C ++的新手,我刚刚学习了一些Java基础知识后开始学习它。 我有预先存在的代码,因为它已经重载>>运算符,但是在看了很多教程并试图理解这个问题之后,我想我会问这里。

Rational 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

该函数来自一个名为Rational的预先存在的类,它将两个int作为参数。以下是重载>>

的函数
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;
 }

就像我说的那样,我对整个重载操作员的事情都很陌生,并且在这里找人可以指出我如何使用这个功能的正确方向。

2 个答案:

答案 0 :(得分:10)

Rational n1();更改为Rational n1;。你遇到了most vexing parseRational n1();不会实例化Rational对象,但声明名为n1函数会返回Rational个对象。

答案 1 :(得分:1)

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

这不会创建新对象,但会声明一个不带参数的函数并返回Rational 你可能意味着

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