复制具有链表成员的派生类的构造函数

copy constructor for derived class with linklist member

本文关键字:派生 构造函数 成员 链表 复制      更新时间:2023-10-16

我一直在看派生类的复制构造函数示例,但我真的不明白我应该如何写这个。

我有三类LinkListCDMedia

我已经为 MediaLinkList 编写了复制构造函数,但没有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
}

使用下面由 @Remy Lebeau 提供的解决方案

CD::CD(const CD &obj) :Media(obj), Cd(obj.Cd) {}