これは私のプログラムです。私はタイプStudentのオブジェクトを作成し、次に学生にアイテムをチェックアウトさせる必要があります。そして、私はそのアイテムをチェックアウトさせるためにオーバーロードされた加算演算子を使用しています。オーバーロードされた加算演算子を使用するのが難しい
main.cppに:私がしようとすると、最小と簡素化、このプログラムを維持するために、ヘッダーファイル内のすべての私のクラスのdefintionsを定義し
#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;
}
。
Student.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
、メインから、そのは間違ったことを出力します。最初の名前と最後の名前の後に2つのスペースを続けてidを出力する代わりに、番号:-858993460を出力します。これはメモリリークの問題などがありますが、コピーコンストラクタ、オーバーロードされた代入演算子、およびデコンストラクタがすべて正しく定義されていることは間違いありませんが、それらを見ることができます。
私はここでかなり切望しているので、私はすべての助けに感謝します。ありがとう。
修正しました。ありがとうございました。 – Jacob