代码是打印对象的内存位置而不是对象本身

问题描述 投票:0回答:3
#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 <<”“;”有关。但我不是百分百肯定。有人可以解释如何解决这个问题以及为什么它会起作用?提前致谢!

c++ object linked-list
3个回答
2
投票

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;
}

0
投票

要打印指针的值,您需要使用*取消引用它。

所以,你会想要使用std::cout << *(temp->data);来获得data的值,这是一个Person*

更多关于dereferencing pointers


0
投票

与cout的temp->data解析为Person指针。要解决此问题,您可以在Person指针(即对象)上调用一个返回字符串的方法

© www.soinside.com 2019 - 2024. All rights reserved.