簡體   English   中英

類型“ const char *”的參數與類型“ Person”的參數不兼容

[英]Argument of type “const char*” is incompatible with parameter of type “Person”

#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 p ,則LinkedList對象將有一個指向垃圾的指針。 如果你打電話給delete ALinkedList::InsertAtHead ,現在main的指針指向垃圾。 更何況Node可能會遇到垃圾指針的所有問題,以及它可能從LinkedListmain下面拉出地毯的所有方式!

除非您確實需要原始指針來進行瘋狂的優化,否則我強烈建議您閱讀有關資源獲取的內容,即初始化 ,並將其牢記在心–與使用原始指針相比,這有點乏味,但是它將為您省去很多麻煩路。

InsertAtHead函數采用一個類型為Person*參數。 您要傳遞四個參數。 而是將其傳遞給Person的指針。

不過,您確實不應該以這種方式使用裸指針。 這使得管理所指對象的生命周期極為困難。 您的InsertAtHead函數采用指向現有Person對象的指針並將其存儲。 如果該Person對象曾經被銷毀,則該指針將變為無效。 這只是自找麻煩。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM