[英]C++ How do I print an object?
I have created a constructor我创建了一个构造函数
Location(double xIn,double yIn,string placeIn,int timeIn)
: x(xIn),y(yIn) ...so on {
Say I want to print Location home(x,y,place,time);假设我想打印 Location home(x,y,place,time); that's in the main()
.那在main()
。
How would I do so?我该怎么做? I've been searching around and was told to use operator<<
.我一直在四处寻找并被告知使用operator<<
。 How would I implement this?我将如何实现这一点?
UPDATE: After creating some get methods and I tried doing,can't exactly compile it because of the problem更新:在创建了一些 get 方法并且我尝试这样做之后,由于问题无法完全编译它
ostream &operator<<(ostream & o, const Location & rhs){
o << rhs.getX() << "," << rhs.getY() << "," << rhs.getPlace() << "," << rhs.getTime();
return o; }
Here is the stencil for overloading operator<<
:这是用于重载operator<<
的模板:
class Any
{
public:
friend std::ostream& operator<<(std::ostream& output, const Any& a);
private:
int member;
};
std::ostream&
operator<<(std::ostream& output, const Any& a)
{
output << a.member;
return output;
}
This one possible stencil, there are other possibilities.这是一种可能的模板,还有其他的可能性。 Search the internet for "c++ stream insertion operator overload example" for other implementations.在 Internet 上搜索“c++ 流插入运算符重载示例”以获取其他实现。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.