簡體   English   中英

收到錯誤“在拋出'std::bad_alloc'what() 的實例后調用終止:std::bad_alloc”

[英]getting error "terminate called after throwing an instance of 'std::bad_alloc' what(): std::bad_alloc"

這是我在 Stackoverflow 上的第一篇文章,我希望我能找到解決我問題的方法。

這是課程歌曲的主要內容,它在其中獲取元數據(長度、年份、流派)。 我認為問題來自函數 enumToString 但我不確定:/

Song::Song(Artist artist, string title)
{
    an_artist = &artist;
    a_title = title;
}


Artist Song::artist() const
{
    return *an_artist;
}

void Song::artist(Artist artist)
{
    an_artist = &artist;
}

string Song::title() const
{
    return a_title;
}

void Song::title(string title)
{
    a_title = title;
}

Metadata *Song::metadata()
{
    return &a_metadata;
}

// converting enum to string
const string enumToString (Genre val)
{
    switch (val)
    {
        case Genre::Funk:
            return "Funk";
        case Genre::Soul:
            return "Soul";
        case Genre::Rap:
            return "Rap";
        case Genre::Rock:
            return "Rock";
        case Genre::Unknown:
            return "Unknown";
        default:
            return "Not recognized!";
    }
}

string Song::info()
{
    int minutes = a_metadata.lengthInSeconds / 60;
    int seconds = a_metadata.lengthInSeconds % 60;


    cout << "( "<< a_title << " ) " << "by " << an_artist->name()
                  << " Genre: " << enumToString(a_metadata.a_genre) << ","
                  << " Length: "<< minutes << ":" << seconds << ","
                  << " Published: " << a_metadata.publishedInYear;
    return "";
}

我正在嘗試打印歌曲,但是在第一首歌曲之后我收到了這個錯誤,我真的不知道問題出在哪里。 這是我第二次用 C++ 編碼 ^^ 提前謝謝

Moez of fawez
fawez : Moez, Sofiene, Rostom, Amine, 

( bara hakeka ) by �>��) Genre: Funk, Length: 15:0, Published: 1980
terminate called after throwing an instance of 'std::bad_alloc'
  what():  std::bad_alloc

注意:我在這里發布答案,這樣人們就不必通過評論來找到它。

在artist.cpp的“addSong”函數中:

void Artist::addSong(Song *song)
{
    the_songs.push_back(song);
    song->artist(*this); // line I will be referencing
}

您正在傳遞對象的“this”指針。 每個對象都有自己的“this”指針,它可以訪問自己的內存地址。 在此處了解更多信息: https : //www.tutorialspoint.com/cplusplus/cpp_this_pointer.htm

然而,在來自 song.cpp 的函數“藝術家”中:

void Song::artist(Artist artist)
{
    Artist artistou = artist;
}

旁注:請在這種情況下使用 setter 和 getter(封裝)。 即 void set_artist(...) 和 Artist get_artist()。

該參數不反映您傳入指向對象內存地址的指針。 另外,因為artistou是在這個函數內部本地聲明和定義的,一旦程序離開這個函數的范圍,這個變量life也會從你的計算機內存中消失。 這個變量應該在 song.h 中定義為:

Artist *artistou = new Artist();

然后從不再使用的內存中刪除 [] 以避免內存泄漏。

總的來說,請回顧一些關於 C++ 的良好編碼實踐。 正如您所說,您是新手,我將刪除一些我認為您可以從學習中受益的重要主題的鏈接。

繼承: https : //en.cppreference.com/book/intro/inheritance

封裝和 Getter 和 Setter: https : //www.w3schools.com/cpp/cpp_encapsulation.asp

動態內存管理: https : //en.cppreference.com/w/cpp/memory

我希望這有幫助!

暫無
暫無

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

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