首页 > 解决方案 > 如何在 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;
}

标签: c++objectpointerslinked-listdereference

解决方案


您取消引用指针的事实是一个红鲱鱼: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
}

推荐阅读