我一直在寻找派生类的复制构造函数的例子,但我真的不明白我应该怎么写这个。
我有三个课程LinkList
,CD
和Media
。
我为Media
和LinkList
但不是CD
编写了副本构造函数,它是Media
的派生类,其成员变量的LinkList
。
请不要对此提供任何帮助。
class LinkList
{
private:
struct ListNode
{
T value1;
struct ListNode *next;
};
ListNode *head; // List head pointer
public:
//***Constructor***
LinkList();
LinkList(const LinkList<T> &);
//***Destructor***
~LinkList();
//***LinkList Operations***
//....operation functions
};
//***Constructor***
template <class T>
LinkList<T>::LinkList()
{
head = NULL;
}
//***Copy Constructor***
template <class T>
LinkList<T>::LinkList( const LinkList &listObj )
{
head = NULL;
ListNode *nodePtr;
nodePtr = listObj.head;
while(nodePtr != NULL)
{
appendNode(nodePtr->value1);
nodePtr = nodePtr->next;
}
}
class Media
{
private:
string title;
string length;
public:
//***Constructors***
Media();
Media(string, string);
Media(const Media &obj);
//***destructor***
~Media();
//***Mutators***
void setTitle(string);
void setLength(string);
//***Accessors***
string getTitle();
string getLength();
//Overloaded Operators
bool operator < (const Media &);
bool operator > (const Media &);
bool operator != (const Media &);
bool operator == (const Media &right);
};
/*****Implimentation*********/
//***Constructors***
Media::Media()
{
title = " ";
length = " ";
}
//***Constructors***
Media::Media(string t, string l)
{
title = t;
length = l;
}
//***Copy Constructor***
Media::Media(const Media &obj)
{
title = obj.title;
length = obj.length;
}
//LinkList structure for CD class
struct CdContence
{
string song;
string length;
};
class CD : public Media
{
public:
LinkList<CdContence> Cd;
//***Constructors***
CD(string, string);
CD();
//***destructor***
~CD();
//***Mutators***
void setCD(string, string, string, string);
//***Accessors***
LinkList<CdContence> getCD();
//Overloaded Operators
bool operator < (CD &);
bool operator > (CD &);
bool operator != (CD &);
bool operator == (CD &);
};
/*****Implimentation*********/
//***Constructors***
CD::CD(string T, string L)
{
setTitle(T);
setLength(L);
LinkList<CdContence>Cd;
cout<<"CD CONSTRUCTOR2"<<endl;
}
CD::CD() : Media()
{
LinkList<CdContence>Cd;
cout<<"CD CONSTRUCTOR"<<endl;
}
CD::CD(const CD &obj) :Media(obj)
{
//not sure what to put here since the member variable is
// a linklist
}
答案 0 :(得分:1)
使用@Remy Lebeau提供的解决方案
CD::CD(const CD &obj) :Media(obj), Cd(obj.Cd) {}