4

嗨,我对 C++ 比较陌生,在学习了一些 Java 基础知识后,我才开始学习它。我有预先存在的代码,如果它使>>操作员过载,但是在观看了许多教程并试图理解这个问题之后,我想我会在这里问。

合理的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 的预先存在的类,它接受两个ints 作为参数。这是重载的函数>>

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

就像我说的那样,我对整个重载运算符的事情是新手,并且认为这里的某个人能够为我指出如何使用这个函数的正确方向。

4

2 回答 2

10

更改Rational n1();Rational n1;。你遇到了最令人头疼的 parseRational n1();不实例化一个Rational对象,而是声明一个名为返回对象的函数n1Rational

于 2013-04-29T19:42:59.257 回答
1
// create a Rational Object.
    Rational n1();

这不会创建新对象,而是声明一个不带参数的函数并返回Rational 您可能的意思

// create a Rational Object.
    Rational n1;
    cin>>n1;
于 2013-04-29T19:49:02.597 回答