64,654
社区成员
发帖
与我相关
我的任务
分享
template <typename T>
void linkedQueue<T>::copy(const linkedQueue<T>& q)
{
// qback moves through the list we are building and
// winds up at the rear of our new list. p
// moves through the list we are copying
node<T> *newNode, *p = q.qfront;
// initially, the list is empty
qfront = qback = NULL;
// nothing to do if p is NULL
if (p != NULL)
{
// create the first node in the queue and assign
// its addres to qback
qfront = qback = getNode(p->nodeValue);
// move forward in the list we are copying
p = p->next;
// copy remaining items
while(p != NULL)
{
// insert new node at the back
newNode = getNode(p->nodeValue);
qback->next = newNode;
// qback is the new node
qback = newNode;
// move to the next node of the list we are copying
p = p->next;
}
}
// the size of the new list is the size of q
qsize = q.qsize;
}
template <typename T>
linkedQueue<T>::linkedQueue(const linkedQueue<T>& obj)
{
// call copy() and pass the pointer to the front of
// the linked list in obj
copy(obj);
}
int a(5); //调用构造函数
int b(a); //调用拷贝构造函数,把a的值给b
a = 6; //调用赋值“=”操作符改变a的值,至于a原来的值,不需要我们关心
cout << a;
cout << b;
#include <iostream.h>
class A
{
public:
~A(){cout << "析构\n";}
A(int iValue){cout << "构造\n";value = iValue;}
int value;
};
int main()
{
A a(4);
A b(a);
a = b; //观察输出,发现调用了两次析构,就是对象a和b的析构,而屏蔽
return 0; //了a=b这个赋值语句发现仍然是两次析构,也就是说,尽管
//赋值覆盖了a原来的值,但是并没有发生析构,因为赋值只是在
//a已有的内存空间上进行成员值的“重写”罢了,并不是释放掉
//a原有的空间,而另开辟一块来存放b的成员
}
Test& operator =(const Test& rhs)
{
Test(rhs).swap(*this);
}
void swap(Test& rhs)
{
std::swap(p_, rhs.p_);
}
这个swap是标准库中的吗?在哪个头文件里?谢谢哦,初级水平呵呵。
class Test{
int* p_;
public:
Test() : p_(new int(0)){}
Test(const Test& rhs) : p_(new int(*rhs.p_)){}
Test& operator =(const Test& rhs)
{
Test(rhs).swap(*this);
}
~Test(){delete p_;}
void swap(Test& rhs)
{
std::swap(p_, rhs.p_);
}
};