c++ - 类型 "const char*"的参数与类型 "Person"的参数不兼容

标签 c++ error-handling 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("Bob", 22, 145, 70);                 list->Print();      //2

我收到问题中所述的错误。我是 C++ 的新手,不明白为什么会抛出这个错误。错误发生在“list->InsertAtHead("Bob", 22, 145, 70);”行。这对我来说没有意义,因为如果我在 InsertAtHead 函数中指向 Person 对象,它不应该将 Person 类中的四个参数与 Person 对象一起传递吗?我将如何解决这个问题并消除错误?

最佳答案

LinkedList::InsertAtHead 的定义是:

void InsertAtHead(Person*A) { /* ... */ }

这意味着您必须给它一个指向 Person 对象的指针。你这样调用它:

list->InsertAtHead("Bob", 22, 145, 70);

这是给它一个 const char* 和一堆整数。我猜你想这样做:

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

当然,你也可以这样做:

Person *p = new Person("Bob", 22, 145, 70);
list->InsertAtHead(p);

但这凸显了您设计中的一个潜在缺陷:谁拥有指针 *p?如果你从 main 调用 delete pLinkedList 对象将有一个指向垃圾的指针。如果你在 LinkedList::InsertAtHead 中调用 delete A,现在 main 有一个指向垃圾的指针。更不用说 Node 可能因垃圾指针而产生的所有问题,以及它可以从 LinkedListmain< 下移除地毯的所有方法!

除非您真的需要原始指针来进行一些疯狂的优化,否则我强烈建议您继续阅读 resource acquisition is initialization并将其牢记在心——它比使用原始指针更乏味一点,但它会让你在以后的道路上省去很多麻烦。

关于c++ - 类型 "const char*"的参数与类型 "Person"的参数不兼容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49080885/

相关文章:

c++ - 使用 static_assert 检查传递给宏的类型

c# - 如何防止ServiceStack EventLogFactory记录DEBUG事件?

vb.net - 从错误对象获取错误的位置

java - 没有尾部字段的 LinkedList 陷入无限循环

c++ - Word-Net线程安全

c++ - 用常量初始化数组不起作用

c++ - 对 void 及其含义的困惑。

python - 在Tkinter中尝试约会-Python

c - 我陷入链表的无限循环

algorithm - 什么时候双向链表比单向链表更高效?