您好我對C++來說比較陌生,在學習一些Java基礎知識之後我纔開始學習它。 我有預先存在的代碼,它已經超載了>>
運營商,但是在看了很多教程並試圖理解這個問題後,我想我會在這裏問。新的C++和重載操作符,不確定如何使用函數
理性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
的功能是從一個稱爲理性預先存在的類,它需要兩個int
S作爲參數。下面是函數重載>>
:
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;
}
就像我說我是新來的這整個重載運營商的事情上,拿捏有人在這裏將能夠指出我在正確的方向上如何使用此功能。
哇!如果它出現在我的代碼中,我絕不會追蹤它。 – 2013-04-29 19:46:38
@Jesse:很好! – 2013-04-29 19:47:10
@NemanjaBoric,當然可以。這通常與打開編譯器警告一樣簡單。 – chris 2013-04-29 19:47:15