【问题标题】:Code is printing memory location of object rather than the object itself代码正在打印对象的内存位置而不是对象本身
【发布时间】:2018-03-03 06:57:05
【问题描述】:
#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 data

【问题讨论】:

标签: c++ object linked-list


【解决方案1】:

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

【讨论】:

  • 好吧,第一部分对我来说很有意义,但我对函数重载感到困惑。为什么必须这样做?是否有另一个链接可以参考我如何更好地做到这一点?谢谢!
  • @Fall0ut,在stackoverflow.com/questions/4421706/… 浏览答案。希望它会有所帮助。
【解决方案2】:

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

因此,您需要使用std::cout &lt;&lt; *(temp-&gt;data); 来获取data 的值,即Person*

更多关于dereferencing pointers的信息。

【讨论】:

    【解决方案3】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-11-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多