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

use*_*446 4 c++ overloading operators

嗨我是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;
}}
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

该函数来自一个名为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;
    }
Run Code Online (Sandbox Code Playgroud)

在看了几个教程后,我正试图像这样使用它.(我得到的错误是"Ambiguous overload for operator>>std::cin>>n1:

int main () {
// create a Rational Object.
    Rational n1();
    cin >> n1;
 }
Run Code Online (Sandbox Code Playgroud)

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

Jes*_*ood 10

更改Rational n1();Rational n1;.你遇到了最令人烦恼的解析.Rational n1();不实例化一个Rational对象,但是声明了一个函数命名n1它返回一个Rational对象.

  • @NemanjaBoric,当然可以.它通常像打开编译器警告一样简单. (2认同)