概念:复制构造函数是一种特殊的构造函数,每当创建一个新对象并使用另一个对象的数据对其进行初始化时,都会调用该副本构造函数。
有时候C ++中的按成员分配行为是可以完全接受的,但是在当按成员分配不能使用的时候,比如下面这个例子
#ifndef STUDENTTESTSCORES_H
#define STUDENTTESTSCORES_H
#include <string>
using namespace std;
const double DEFAULT_SCORE = 0.0;
class StudentTestScores
{
private:
string studentName; // The student's name
double *testScores; // Points to array of test scores
int numTestScores; // Number of test scores
// Private member function to create an
// array of test scores.
void createTestScoresArray(int size)
{
numTestScores = size;
testScores = new double[size];
for (int i = 0; i < size; i++)
{
testScores[i] = DEFAULT_SCORE;
}
public:
// Constructor
StudentTestScores(string name, int numScores)
{
studentName = name;
createTestScoresArray(numScores);
}
// Destructor
~StudentTestScores()
{
delete [] testScores;
}
// The setTestScore function sets a specific
// test score's value.
void setTestScore(double score, int index)
{
testScores[index] = score;
}
// Set the student's name.
void setStudentName(string name)
{
studentName = name;
}
// Get the student's name.
string getStudentName() const
{
return studentName;
}
// Get the number of test scores.
int getNumTestScores()
{
return numTestScores;
}
// Get a specific test score.
double getTestScore(int index) const
{
return testScores[index];
}
};
#endif
对于上面这个程序的一个潜在安全问题是testScores是一个指针,createTestScoresArray成员函数出现了对于指针的一个关键操作:它动态分配testScores的内存并给它分配默认值。看下面这个图
想想当StudentTestScore对象被创建并用student1初始化的时候下列语句会发生什么
StudentTestScore student2 = student1;
在上面的语句中,student2的构造函数并没有被调用。而是成员分配符占了他的位置,把在student1里面的每一个变量拷贝到student2里去。看下面这个表
在这种情况来讲,两个对象都可以控制储存在数组中的值来影响另一个对象中的现实结果