构造函数= default;_Miles的C++学习笔记#4.3 复制构造函数

概念:复制构造函数是一种特殊的构造函数,每当创建一个新对象并使用另一个对象的数据对其进行初始化时,都会调用该副本构造函数。

有时候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的内存并给它分配默认值。看下面这个图

83a742d9d574f0e0e8557d1a8d0a5089.png

想想当StudentTestScore对象被创建并用student1初始化的时候下列语句会发生什么

StudentTestScore student2 = student1;

在上面的语句中,student2的构造函数并没有被调用。而是成员分配符占了他的位置,把在student1里面的每一个变量拷贝到student2里去。看下面这个表

b575761c61ed4b5a87e1e11af36efc93.png

在这种情况来讲,两个对象都可以控制储存在数组中的值来影响另一个对象中的现实结果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值