c++和重载运算符的新手,不确定如何使用该函数
New to c++ and Overloading operators, unsure how to use the function
嗨,我对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;
相关文章:
- 不确定如何装饰我的C++库代码以在 C 中使用
- 不确定如何使用enable_if以及为什么它很重要
- 不正确的演员 - 是铸件还是不确定行为的使用
- 使用C和C 一起使用函数错误的不确定引用
- 尝试使用函数时会出现错误,不确定为什么
- 更改对象并将其在同一表达式中使用它是不确定的行为,但是子表达式由逗号运算符分开
- 试图在每次输出后使用一个函数摆脱'0',但不确定我可以返回什么
- 正在使用C 中的插入后变量不确定行为访问数组的元素
- 尝试修改 sqlite3 插入以返回 PK。 不确定如何使用 sqlite3 专门执行此操作
- 使用非原子布尔时的不确定行为
- OpenCV符号使用GCC 5.1不确定
- 如果没有使用使用代码的链接,则对G 中的静态常规成员的不确定引用
- 我不断收到错误"变量'b'未初始化正在使用,我不确定如何解决它
- 不确定如何使用我的类和命名空间创建对象?c++
- 什么是C++中的不确定行为?它与未定义的行为有何不同
- 不确定如何使用另一个类中的对象创建带有参数的构造函数
- 不确定要使用哪种数据结构
- 不确定如何使用模板调用类函数
- c++和重载运算符的新手,不确定如何使用该函数
- 不确定如何使用QtTest