私はC++を使ってリンクリストプロジェクトのコードを書いています。リンクリストとコンストラクタ
#include <iostream>
#include <string>
using namespace std;
struct song1
{
string song;
string title;
song1* next;
};
class song_list
{
protected:
song1* head;
int length;
public:
song_list();
bool insertSong (song1* newSong, int track);
//bool removeSong (int track);
void printSong();
~song_list();
};
song_list::song_list()
{
head->song = "No data";
head->title = "No data";
head->next = NULL;
length = 0;
}
bool song_list::insertSong (song1* newSong, int track)
{
int count=0;
if ((track<=0) || (track>length+1))
{
cerr<<"\nThe given track is out of range";
return false;
}
if (head->next == NULL)
{
head->next= newSong;
length++;
return true;
}
count =0;
song1* p = head;
song1* q = head;
while (q)
{
if (count==track)
{
p->next = newSong;
newSong-> next = q;
length++;
return true;
}
p=q;
q=p->next;
count++;
}
if (count==track)
{
p->next = newSong;
newSong-> next = q;
length++;
return true;
}
cerr<<"Song was not added in the list";
return false;
}
void song_list::printSong()
{
int count = 0;
song1* p=head;
song1* q=head;
cout<<"\n------------------\n";
cout<<"Song playlist\n";
while (q)
{
p = q;
cout<<"\n------------------\n";
cout<<"\tPosition "<<count<<endl;
cout<<"\tsong "<<p->title<<endl;
cout<<"\tArtist "<<p->song<<endl;
q= p->next;
count++;
}
}
song_list::~song_list()
{
song1* p= head;
song1* q=head;
while (q)
{
p = q;
q = p->next;
if (q) delete p;
}
}
メインファイル:
#include <iostream>
#include <string>
#include "LinkedListh.h"
using namespace std;
int main()
{
int choice,repeat,trc;
song1* info;
song_list func;
do
{
cout<<"1. Add song "<<endl;
cout<<"2. Delete song "<<endl;
cout<<"3. Show song "<<endl;
cout<<"4. Search song "<<endl;
cin>>choice;
switch (choice)
{
case 1:
cout<<endl<<"Artist: ";
getline (cin,info->song);
//getline (cin,info->song);
cout<<endl<<"Song Title: ";
getline (cin,info->title);
cout<<"Song number: "<<endl;//ask the user to put the song number
//if artist doesnt exist the user should put 1.
//else user should put what number the song is.
cin>>trc;
func.insertSong(info,trc);
break;
case 3:
func.printSong();
break;
}
cout<<"Repeat? 1.Yes 2.No"<<endl;
cin>>repeat;
}while (repeat == 1);
return 0;
}
コードは正常にビルドすることができますが、私はプログラムを実行すると、それは「動作を停止しました示し、これは、これまで
ヘッダファイル私のコードです"メッセージ。私はエラーが私のコンストラクタにあることを理解する。それは文字列を初期化する正しい方法ですか?なぜなら私がコンストラクタを消去すると、「曲とタイトルを最初に初期化する必要がある」というメッセージが出てきたからです。私はC++でまだ新しいので、ビットごとにリンクリストを学習しています。ちなみに、私はリンクされたリストを正しくやっていますか?ありがとう!
'song_list'メンバー' head'は、私は、コンストラクタを使用してsong1のメモリを割り当てるしようとしていた同様の問題 – makadev
を持ってあります。私はそれを正しく行っているかどうかはわかりません。 –
"new ClassName()"と似たようなものがあるときは、コンストラクタが呼び出されます。曲1 *情報=新しい曲1();コンストラクタを呼び出してメモリをすべて確保します。しかし、スマートポインタは通常、allcoation yourlsef(std :: make_unique();) –
xaxxon