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



嗨,我对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;
    }

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

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

就像我说的,我对重载运算符这件事还很陌生,我想这里的人会为我指明如何使用这个函数的正确方向。

Rational n1();更改为Rational n1;。你遇到了最麻烦的解析。Rational n1();不实例化Rational对象,而是声明一个名为n1函数,该函数返回一个Rational对象。

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

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

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

相关内容

最新更新