如何实现指针的<<和>>?

How to implement << and >> for pointers?

本文关键字:lt gt 指针 何实现 实现      更新时间:2023-10-16

我需要得到'<lt;'和'>>'为指针工作,正如我在下面为我的驱动程序编码的那样。

int main()
{
using namespace std;

cout << "Welcome to My TrashCan Program!" << endl;
TrashCan myCan;
TrashCan yourCan;
TrashCan empty( 0, 0 );
TrashCan * ptrCan = new TrashCan( 0, 0 );
TrashCan * nullCan = NULL; // pointer to null
// using pointers here
cin >> ptrCan;
cin >> nullCan;  // 
cout << ptrCan << endl;
cout << nullCan << endl;  //
return 0;}

我假设我必须在某个地方实现这些功能,但不太确定如何实现:

friend std::ostream& operator <<( std::ostream& outs, const TrashCan * drive );
friend std::istream& operator >>( std::istream& ins, TrashCan * & drive );

cin读取指针几乎永远不会起作用。这就是为什么默认情况下该语言不允许您使用。类似的线路

cin >> ptrCan;

如果允许的话,会丢失对几行之前从new TrashCan( 0, 0 );获得的对象的跟踪(即泄漏)。

请解释一下你真正想做什么。