如何在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
}
,

您得到的错误不是您不能取消引用对象指针,而是没有指定如何打印该对象指针。无论指向什么,指向标准库未知类型的指针都可以用相同的方式打印,但是对于实际对象和对象引用,您必须指定要在屏幕上显示的内容。您可以通过为类重载products运算符来做到这一点,例如:

<<