[英]Operator overloading and references to objects
I have some code which overloads the << operator to print out some data I used this website and pretty much copied the code 我有一些代码重载<<运算符来打印出我使用过这个网站的一些数据并且几乎复制了代码
https://msdn.microsoft.com/en-us/library/1z2f6c2k.aspx https://msdn.microsoft.com/en-us/library/1z2f6c2k.aspx
I can get the code to work properly but not for my given example. 我可以让代码正常工作,但不是我给出的例子。
As you can see by the link: 正如您可以通过链接看到的:
// overload_date.cpp
// compile with: /EHsc
#include <iostream>
using namespace std;
class Date
{
int mo, da, yr;
public:
Date(int m, int d, int y)
{
mo = m; da = d; yr = y;
}
friend ostream& operator<<(ostream& os, const Date& dt);
};
ostream& operator<<(ostream& os, const Date& dt)
{
os << dt.mo << '/' << dt.da << '/' << dt.yr;
return os;
}
int main()
{
Date dt(5, 6, 92);
cout << dt;
}
But for my example I create pointers to the objects rather than the values directly, so I'd have something like: 但是对于我的例子,我创建指向对象的指针而不是直接创建值,所以我有类似的东西:
Item *it;
it = new Screwdriver("big", 11);
cout << it;
But this then only prints out the pointer! 但这只会打印出指针! how do I dereference this? 我如何取消引用这个? or is this even the best way to do it ? 或者这是最好的方法吗?
使用*
运算符解反指针,如下所示:
std::cout << *it;
See code below: 见下面的代码:
Item *it;
it = new Screwdriver("big", 11);
cout << *it;
C++ has dereference operator *
to go from pointer to the value it points to. C ++有取消引用运算符*
从指针指向它指向的值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.