Hi I am rather new to C++, I have just started learning it after learning some Java basics.
I have pre-existing code were it has overloaded the >>
operator, however after watching many tutorials and trying to understand the issue, I thought I would ask here.
Rational cpp file:
#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 file:
#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
The function is from a pre-existing class called Rational which takes two int
s as parameters. Here is the function to overload >>
:
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;
}
And I'm trying to use it like this, after seeing a few tutorials. (The error I am getting is "Ambiguous overload for operator>>
in std::cin>>n1
:
int main () {
// create a Rational Object.
Rational n1();
cin >> n1;
}
Like I said I'm new to this whole overloading operators thing, and figure someone here would be able to point me in the right direction on how to use this function.
Change Rational n1();
to Rational n1;
. You've ran into the most vexing parse. Rational n1();
does not instantiate a Rational
object, but declares a function named n1
which returns a Rational
object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With