c++ - 代码正在打印对象的内存位置而不是对象本身

标签 c++ object linked-list

#include <iostream>
#include <string>
using namespace std;

class Person{
private:
    string name;
    int age, height, weight;
public:
    Person(string name = "empty", int age = 0, int height = 0, int weight = 0) {
        this->name = name;
        this->age = age;
        this->height = height;
        this->weight = weight;
    }
};

class Node {
public:
    Person* data;
    Node* next;
    Node(Person*A) {
       data = A;
        next = nullptr;
    }
};

class LinkedList {
public:
    Node * head;
    LinkedList() {
        head = nullptr;
    }

    void InsertAtHead(Person*A) {
        Node* node = new Node(A);
        node->next = head;
        head = node;
    }

    void Print() {
        Node* temp = head;
        while (temp != nullptr) {
            cout << temp->data << " ";
            temp = temp->next;
        }
        cout << endl;
    }
};

int main() {
    LinkedList* list = new LinkedList();

    list->InsertAtHead(new Person("Bob", 22, 145, 70));    list->Print();
}

当我运行 Print 方法时,我的代码将打印存储 Person 的内存位置。我试着用调试器运行代码,但我仍然很困惑,我是 C++ 的新手,而且只是一名大学生。我猜这与我的打印类和特别是“cout << temp->data <<”“;”的行有关但我不是 100% 确定。有人可以解释如何解决这个问题以及为什么它会起作用吗?提前致谢!

最佳答案

Node::data 的类型是Person*。这是有道理的

cout << temp->data << " ";

只打印一个指针。

如果你想打印对象,你必须使用:

cout << *(temp->data) << " ";

但是,在使用它之前,您必须定义一个支持该操作的函数重载。定义具有以下签名的函数:

std::ostream& operator(std::ostream& out, Person const& person)
{
   // Print the details of person.

   // Return the same ostream object
   return out;
}

关于c++ - 代码正在打印对象的内存位置而不是对象本身,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49081568/

相关文章:

c++ - 为什么这个 C++ 程序如此之快?

c++ - 链表赋值运算符

class - 如何从 Python 2.7 中的 set() 中删除重复的类对象?

c - 释放内存、函数

c++ - 确定比较中文字的有效类型

c++ - 将 SecByteBlock 中的 key 传递给算法?

javascript - 将参数传递给事件处理程序

java - 我的空指针异常

C:如何打印出tree_node数据?

Java链表add方法