c++ - 如何在 C++ 中取消引用指针对象?
问题描述
运行此程序时出现错误?
cout << *head << endl;
为什么我们不能取消引用对象指针?就像我们在 int 数据类型中所做的那样:
int obj = 10;
int *ptr = &obj;
cout << *ptr << endl; //This will print the value 10 by dereferencing the operator!
但不是在对象为什么?
#include <iostream>
using namespace std;
class Node
{
public:
int data;
Node *next;
Node(int data)
{
this->data = data;
this->next = NULL;
}
};
int main() {
Node N1(10);
Node *head = &N1;
cout << &N1 << endl;
cout << head << endl;
cout << *head << endl;
cout << &head << endl;
}
解决方案
您取消引用指针的事实是一个红鲱鱼:std::cout << N1 << endl;
出于同样的原因不会编译。
你需要为std::ostream& operator<<(std::ostream& os, const Node& node)
你的类实现(在全局范围内)Node
,在函数体中你会写一些类似的东西
{
os << node.data; // print the data
return os; // to enable you to 'chain' multiple `<<` in a single cout statement
}
推荐阅读
- c# - Python.NET 如何在 Python 中执行 .NET 代码?它是如何收集垃圾的?
- mysql - 如何对 x 个相同的 MySQL SUM 表求和?
- javascript - 无法使用 jQuery 使输入行为作为选项卡
- java - Eclipse PowerMock 覆盖与 ECLEmma
- javascript - 如何防止 pwa 虚拟键盘破坏我的布局?我正在使用 vuejs
- ios - 如何在 iOS 上录制视频时保存 TrueDepth 数据?
- headless - 如何从命令提示符运行 Maven Serenity 测试以进行无头浏览器测试?
- javascript - React axios.get not working it's says failed to compile
- java - 使用 ChronoUnit 从 GPS 点计算平均速度
- websphere-liberty - 如何在 websphere liberty 中调整 json 日志格式