这是我的程序。我必须制作一个学生类型的对象,然后让学生“ checkout ”一个项目。我正在使用重载的加法运算符让用户 checkout 该项目。
主要.cpp:
#include <iostream>
#include "Student.h"
using namespace std;
int main() {
Student s(54000, "JOHN", "DOE");
cout << "main:" << endl << (s + "Frisbee") << endl << endl;
system("pause");
return 0;
}
我在头文件中定义了我所有的类定义,以尽量使这个程序保持最小和简化。
学生.h:
#ifndef STUDENT_H
#define STUDENT_H
#include <fstream>
#include <string>
#include <iostream>
using namespace std;
class Student {
public:
string firstName;
string lastName;
int id;
int itemsCheckedOut;
int size;
string *array;
Student(int id = 0, string firstName = "", string lastName = "") {
Student::firstName = firstName;
Student::lastName = lastName;
Student::id = id;
itemsCheckedOut = 0;
size = 10;
array = new string[size];
}
Student(const Student &other) {
itemsCheckedOut = other.itemsCheckedOut;
array = new string[itemsCheckedOut];
for (int i = 0; i < itemsCheckedOut; i++) {
array[i] = other.array[i];
}
}
~Student() {
delete[] array;
array = NULL;
}
Student &operator=(const Student &rhs) {
if (this != &rhs) {
firstName = rhs.firstName;
lastName = rhs.lastName;
id = rhs.id;
itemsCheckedOut = rhs.itemsCheckedOut;
delete[] array;
array = new string[size];
for (int i = 0; i < itemsCheckedOut; i++) {
array[i] = rhs.array[i];
}
}
return *this;
}
void CheckOut(const string &item) {
array[itemsCheckedOut] = item;
itemsCheckedOut++;
}
friend ostream &operator<<(ostream &output, const Student &student) {
output << student.id << " " << student.firstName << " " << student.lastName << endl;
if (student.itemsCheckedOut != 0) {
output << student.itemsCheckedOut;
for (int i = 0; i < student.itemsCheckedOut; i++) {
output << " " << student.array[i] << endl;
}
}
else {
output << 0;
}
return output;
}
const Student operator+(const string &item) {
Student s;
s = *this;
s.CheckOut(item);
cout << "class:" << endl << s << endl << endl;
return s;
}
};
#endif
输出:
class:
54000 JOHN DOE
1 Frisbee
main:
-858993460
1 Frisbee
正如你所看到的,从主体来看,它输出了错误的东西。它不是输出 id 后跟两个空格然后是名字和姓氏,而是输出数字:-858993460。这一定是某种内存泄漏问题或其他问题,但我很确定我的复制构造函数、重载赋值运算符和解构函数都已正确定义,但您可以看一下它们。
我非常感谢任何帮助,因为我在这里变得非常绝望。谢谢。
最佳答案
您的实际 operator+
看起来是正确的。但是您的复制构造函数和赋值运算符中存在会导致其发生故障的错误:
- 复制构造函数不设置
size
、id
或名称。 - 复制构造函数应该分配
[size]
项,而不是[itemsCheckedOut]
。 - 赋值运算符不复制
size
。 - 赋值运算符分配了一个维度为旧大小的新数组,可能会立即导致缓冲区溢出。
- checkOut 函数不检查它是否写入超过
大小
。它需要检测这种情况并拒绝结帐或分配更多空间。 (上次您发布有关此项目的问题时我提到了这一点)
关于c++ - 使用重载的加法运算符有困难,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40295804/