复制具有链表成员的派生类的构造函数
copy constructor for derived class with linklist member
我一直在看派生类的复制构造函数示例,但我真的不明白我应该如何写这个。
我有三类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
}
使用下面由 @Remy Lebeau 提供的解决方案
CD::CD(const CD &obj) :Media(obj), Cd(obj.Cd) {}
相关文章:
- 如何委托派生类使用其父构造函数?
- 如果基类包含双指针成员,则派生类的构造函数
- C++:为什么无法在派生类中访问受保护的构造函数?
- C++派生的类构造函数
- 添加自定义析构函数时,Move 构造函数在派生类中消失
- 在没有默认构造函数的情况下创建的派生对象
- 派生类(构造函数具有参数)和基类(构造函数缺少参数)之间没有可行的转换
- 如何在派生构造函数中多次构造基类
- C++(控制台)构造函数和派生类
- 为什么为派生类定义复制构造函数需要定义基类的默认构造函数?
- 在dynamic_pointer_cast后调用派生类的构造函数
- C++ 继承基构造函数,但仍调用默认派生构造函数
- 如何在派生构造函数的大括号中初始化基构造函数?C++
- 如何使派生构造函数将串联值传递给其父构造函数
- dynamic_cast派生构造函数内部
- 复制构造函数-是在派生构造函数之前调用的基本构造函数
- 在派生构造函数中调用基方法是不好的做法
- 基构造函数和派生构造函数之间的歧义
- 派生构造函数警告:永远不会被执行
- 如何将在派生构造函数中生成的参数传递给默认构造函数?