C++复制构造函数以复制成绩
C++ Copy Constructor to Copy Grade
我正忙着写一段代码。代码的功能如下:我有一个班级学生。我想将成绩从大一复制到大一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
与指针一起使用,因为指针基本上满足InputIterator
和OutputIterator
的要求。我要从中复制的数组的开头只是指针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的答案,以获得更具教学性的实现。有许多替代方法可以编写它。所有正确的实现都会初始化所有数据成员(例如 size
和grades
),他们从old_student
复制数据。
第一行中的const
使其更有用,请参阅为什么复制构造函数参数是 const ?。但即使没有const
它也被认为是复制构造函数。
分配新数组看起来浪费内存,可以在对象之间共享数组,但这会使析构函数更加复杂,因为析构函数必须决定何时删除数组。
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 为什么在C++中使用私有复制构造函数与删除复制构造函数
- 当从函数参数中的临时值调用复制构造函数时
- 如果有一个模板构造函数只有一个泛型参数,为什么我必须有一个复制构造函数
- 为什么需要复制构造函数,在哪些情况下它们非常有用
- 使用仅使用一次的变量调用的复制构造函数.这可能是通过调用move构造函数进行编译器优化的情况吗
- 为什么类中的ostringstream类型的成员会导致";调用隐含删除复制构造函数";错误
- 复制构造函数、赋值运算符C++
- std::ofstream 作为类成员删除复制构造函数?
- 复制构造函数C++无法正确复制指针
- 关于复制构造函数的一个棘手问题
- 为什么调用复制构造函数而不是移动构造函数?
- 填充上编译器生成的复制构造函数之间的不一致
- C++ 对象指针数组的复制构造函数
- C++ 基本 CTOR 说明 - 为什么不调用赋值/复制构造函数
- 防止在复制构造函数中隐式调用基构造函数
- 为用户定义的类正确调用复制构造函数/赋值运算符
- 具有已删除移动和复制构造函数的类的就地构造
- 复制构造函数隐式转换问题
- 复制构造函数中的递归调用