复制构造函数的形参,常引用

复制构造函数的形参,常引用

问题描述:

C++中,复制构造函数为什么要用“常引用”作形参,而不是“引用”?谢谢啦

复制构造函数中不能修改的内容,是p的成员变量,即p.pointer的值。也就是说,你不能使p.pointer指向别的位置。即下面这段代码会报错:

Pstu(const Pstu& p)
{
pointer = p.pointer;
p.pointer = NULL; //这句代码会报错
cout << "此时count为:" << (*pointer).count << endl;
(*pointer).count++;
cout << "Pstu1" << endl;
cout << "此时count为:" << (*pointer).count << endl;

}

const只能保护到这一层,至于你再去修改pointer所指向的变量的值,const是保护不了的。

常引用表示你不会修改参数的值,这是一种约定。
例如:

T b = a;

这句话的意思是新建一个和a一样的对象b。执行完了,你自然不希望a的值有任何改变。
在函数声明时加上了const,使用的人即使没看到函数具体实现,也知道你不会修改传入对象的值,这样才能放心地把a的值传给你。

#include "stdafx.h"
#include
#include
using namespace std;

class Pstu;
class student
{
public:
friend class Pstu;
student(int aid, char* pstr) :id(aid), name(pstr)
{
cout << "student构造函数被调用" << endl;
count = 0;
}
~student()
{
cout << "student is destructing..." << endl;
}
void display()
{
cout << "id:" << id << endl;
cout << "name:" << name << endl;

}
private:
unsigned int count;
int id;
char* name;
};
//////////////////////////////////////////////////////////

class Pstu
{
public:
Pstu(student* p) :pointer(p)
{
cout << "Pstu" << endl;
(*pointer).count++;
cout << "此时count为:" << (*pointer).count << endl;
}
Pstu(const Pstu& p)
{
pointer = p.pointer;
cout << "此时count为:" << (*pointer).count << endl;
(*pointer).count++;
cout << "Pstu1" << endl;
cout << "此时count为:" << (*pointer).count << endl;

}
~Pstu()
{
(*pointer).count--;
cout << "此时count为:" << (*pointer).count << endl;
if (!(*pointer).count)
{
cout << "Pstu is destructing..." << endl;
delete pointer;
}
//delete pointer;
}
unsigned int get_count()
{
return (*pointer).count;
}

//student& operator* (){ return pointer; }
//student
operator->(){ return pointer; }
private:
student* pointer;
};
/////////////////////////////////////////////////////////
int main()
{
Pstu p = (new student(1000, "张思源"));
Pstu p1 = p, p2 = p;
cout << p.get_count() << endl;
cout << p1.get_count() << endl;
cout << p2.get_count() << endl;
//p->display();
return 0;
}

既然是通过复制构造函数得到的p1,p2,为什么三个对象中的count 值都是3?是不是复制构造函数中有一句“pointer = p.pointer;”,使得三个对象
private成员变量pointer都指向了和p一样的内存地址?并且在复制构造函数中能修改count的值?这与常引用的初衷不是相矛盾了么?