我有以下代碼。它編譯好,但它表明我的字符串是「E#^$ $ @ $$$$$$$」。 任何想法爲什麼?Ifstream trouble
ifstream InFile(Filename);
if (!InFile)
return false;
std::string Name;
Song *pSong;
for (int a = 0; a < Playlist.size(); a++)
{
delete Playlist[a];
}
Playlist.clear();
while (true)
{
if (!InFile)
break;
pSong = new Song();
std::getline(InFile, Name, '\n');
pSong->File = const_cast<char*>(Name.c_str());
std::getline(InFile, Name, '\n');
pSong->Volume = atof(Name.c_str());
Playlist.push_back(pSong);
}
播放列表:std::vector<Song*>Playlist;
這是不安全的:'pSong-> File = const_cast(Name.c_str());'你現在有一個非const訪問std :: string內部。爲什麼不把'pSong.File'作爲'std :: string'並複製一份?究竟哪個字符串是「那個字符串」,哪個是錯誤的? –
tillaert
什麼是'Song :: File',它爲什麼不是'std :: string'?那麼它應該是'pSong-> File = Name;'(除了事實上你可能不需要用'new'分配'Song' ...) – crashmstr
指針的副本不是內容的副本lookup dlingling pointer/reference) –