问题描述
嘿.是否可能使运算符<<对于原始类型? Fx可以说我每次想写一个int时都要写一个std :: endl.我可以重载运算符<< for int,以便它自动将std :: endl放到输出中?我已经尝试过了,
Hey. Is it possible to overload operator<< for primitive types? Fx lets say that I want to write a std::endl each time want to write a int. Can I overload operator<< for int, so that it automatic puts a std::endl to the output? I have tried with this,
std::ostream& operator<<(std::ostream& strm, int & i)
{
strm << i << std::endl;
return strm;
}
但是它不起作用.我无法回忆起编译器错误消息,但我认为我正在让操作员以任何方式重载所有错误.我尝试调用上述重载运算符<<这样,
but it doesn't work. I cant recall the compiler error message, but I think that I'm getting operator overloading all wrong any ways.I try to call the above overloaded operator<< in this way,
int main()
{
int i = 2;
std::out<<"Here is an int " << i;
return 0;
}
但是它根本不起作用.也许我不能重载POD类型?
But it doesn't work at all. Maybe I can't overload POD types?
推荐答案
正如zabzonk所说,标准库提供了(ostream& int)重载,因此您无法定义另一个.
As zabzonk said, the standard library provides an (ostream&, int) overload so you can't define another.
模拟您在做什么(尽管以目前的形式它是毫无意义的):
To simulate what you were doing (though it is completely pointless in its present form :) :
class EndlinedInteger {
public:
EndlinedInteger(int i) : i(i) { }
friend ostream& operator<<(ostream&, EndlinedInteger const&);
private:
int i;
};
ostream& operator<<(ostream& out, EndlinedInteger const& ei) {
out << ei.i << endl;
return out;
}
int main()
{
EndlinedInteger i = 2;
std::cout<<"Here is an int " << i;
}
这篇关于重载运算符<<用于原始类型.那可能吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!