重载ostream&时出现无效转换错误运算符<<
这是我的 Rational 类的原型
#ifndef RATIONAL_H
#define RATIONAL_H
//forward declaration
class ostream;
class Rational
{
int numerator,denominator;
public:
// the various constructors
Rational();
Rational(int);
Rational(int,int);
//member functions
int get_numerator()const{return numerator;}
int get_denominator()const{return denominator;}
// overloaded operators
// relational operators
bool operator==(const Rational&)const;
bool operator<(const Rational&)const;
bool operator<=(const Rational&)const;
bool operator>(const Rational&)const;
bool operator>=(const Rational&)const;
//arithmetic operators
Rational operator+(const Rational&)const;
Rational operator-(const Rational&)const;
Rational operator*(const Rational&)const;
Rational operator/(const Rational&)const;
//output operator
friend ostream& operator<<(ostream&, const Rational&);
};
#endif //RATIONAL_H
这是重载输出运算符<<的实现在有理数.cpp 中
// friend output operator
ostream& operator<<(ostream& os, const Rational& r)
{
os<<r.get_numerator()<<"/"<<r.get_denominator();
}
,当我尝试编译时,出现以下错误,
g++ -c rational.cpp
rational.cpp: In function ‘ostream& operator<<(ostream&, const Rational&)’:
rational.cpp:81:26: error: invalid conversion from ‘const char*’ to ‘int’ [-fpermissive]
rational.cpp:7:1: error: initializing argument 1 of ‘Rational::Rational(int)’ [-fpermissive]
我希望在将有理数传递给 << 时能够将有理数显示为分子/分母。操作员。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的第一个问题是您尝试将 ostream 声明为类。假设您打算使用
std::ostream
,您不能这样做,它不合法。其一,它是模板专门化的
typedef
,而不是类本身。其次,因为您没有
#include
,所以您没有ostream< 的任何标准
<<
重载的定义/code> 因此,当您尝试<<
字符串文字时,编译器会尝试将字符串文字转换为Rational
类型,因为这是唯一具有一个<<
重载可见。简而言之,您需要
#include
并在使用时用std::
限定ostream
。第三点是您的
operator<<
重载需要返回一些内容。您应该附加一个return os;
语句,或者简单地return
整个流表达式。Your first issue is that you try to forward declare
ostream
as a class. Assuming that you mean to usestd::ostream
, you can't do that, its not legal.For one, it's a
typedef
for a template specialization, not a class itself.Second, because you don't
#include <ostream>
you don't have a definition for any of the standard<<
overloads forostream
so when you try to<<
a string literal, the compiler trys to convert the string literal to aRational
type as that is the only type that has a<<
overload visible.Simply, you need to
#include <ostream>
and qualifyostream
withstd::
where you use it.A third point is that your overload of
operator<<
needs to return something. You should either append areturn os;
statement or simplyreturn
the whole streaming expression.虽然我不确定你为什么会收到这样的错误消息,但我确实发现了一个错误:你应该
在你的朋友函数中添加:。
Although I am not sure why you get such error message, I do found an error: you should add:
in your friend function.