C++复制构造函数以复制成绩

C++ Copy Constructor to Copy Grade

本文关键字:复制 构造函数 C++      更新时间:2023-10-16

我正忙着写一段代码。代码的功能如下:我有一个班级学生。我想将成绩从大一复制到大一2。然后我删除了新生,但新生 2 应该仍然保持新生的成绩。我想/需要使用复制构造函数来做到这一点。但是,我对复制构造函数并不熟悉。这就是我现在所拥有的。有人可以帮我吗?

#include <iostream>
using namespace std;
class Student
{
public:
    int *grades;
    int size;
    Student (unsigned int n) {grades = new int[n]; size = n;}
    Student(const int& other);
    ~Student() {delete[] grades;}
    Student(Student &old_student) {}
};
int main()
{
    Student *freshman = new Student(1);
    freshman -> grades[0] = 8;
    Student *freshman2 = new Student(*freshman);
    delete freshman;
    cout << freshman2 -> grades[0] << endl;
}

提前感谢大家:)

直截了当:

Student(const Student &other)
    : grades(new int[other.size])
    , size(other.size)
{
    std::copy(other.grades, other.grades+other.size, grades);
}

但请记住,使用实际容器将是一个更好的解决方案。此外,拥有公共数据成员并不是封装的最佳主意。另一个轻微的风格是using namespace std;被认为是不好的做法。请注意,我已将复制构造函数参数设置为 const&

这是如何工作的

在初始化列表中,我分配了一个与other Student中的数组具有相同size的新int数组,并将other.size复制到当前(this)学生对象中。我现在拥有一个内部有垃圾的数组及其大小。

在构造函数的主体内部,std::copy现在从other获取实际grades,并将它们复制到我刚刚在初始列表中分配的数组中。制作这样的副本称为深度复制,而不是浅层复制。

这些参数不是 std::copy 指针而不是迭代器吗?

我可以将std::copy与指针一起使用,因为指针基本上满足InputIteratorOutputIterator的要求。我要从中复制的数组的开头只是指针other.grades,我想复制所有内容直到最后(这是数组的开头 + 它的大小,利用指针算法),将副本存储在新grades中。

复制构造函数采用对相同类型的对象的 const 引用。因此,如果您有:

Student(const Student& other);

您认为如何使用 other 参数设置类的值?

http://en.wikipedia.org/wiki/Copy_constructor

一个可能的复制构造函数实现:

Student(const Student &old_student) {
  size = old_student.size;
  grades = new int[size];
  memcpy(grades, old_student.grades, size * sizeof *grades);
}

请参阅risingDarkness的答案,以获得更具教学性的实现。有许多替代方法可以编写它。所有正确的实现都会初始化所有数据成员(例如 sizegrades),他们从old_student复制数据。

第一行中的const使其更有用,请参阅为什么复制构造函数参数是 const ?。但即使没有const它也被认为是复制构造函数。

分配新数组看起来浪费内存,可以在对象之间共享数组,但这会使析构函数更加复杂,因为析构函数必须决定何时删除数组。