重载 operator+ 以添加 2 class 个对象。 "C++ expression must be an unscoped integer or enum type" 错误

Overloading operator+ to add 2 class objects. "C++ expression must be an unscoped integer or enum type" error

我有一个 Student class,它有动态 int 数组 marks 和 int 变量 marksCount。我正在尝试重载 operator+ 以求和 2 Student* 个对象。它应该只是总结他们的分数。

例如,当添加 2 个带有标记 { 2, 3, 4 } + { 1, 5, 2 } 的学生(Student* 个对象)时,我必须有一个带有标记 [=22] 的 Student* 的输出=].

但我的解决方案抛出 C++ expression must be an unscoped integer or enum type 异常 在

Student* s = s1 + s2;行。

我已经阅读过类似的问题和答案,但不幸的是我还没有解决我的问题。也许我不知道 operator+ 是如何工作的?

#include <iostream>

using namespace std;

class Student
{
private:
    int* marks;
    int marksCount;

public:
    Student(int* marks, int marksCount)
    {
        this->marks = marks;
        this->marksCount = marksCount;
    }
    Student* operator+(Student* st)
    {
        int* marks = new int[5];
        for (int i = 0; i < 5; i++)
        {
            marks[i] = this->marks[i] + st->getMarks()[i];
        }

        Student* s = new Student(marks, 5);

        return s;
    }

    int* getMarks()
    {
        return marks;
    }
    void setMarks(int* marks, int SIZE)
    {
        for (int i = 0; i < SIZE; i++)
        {
            this->marks[i] = marks[i];
        }
    }
    int getMarksCount()
    {
        return marksCount;
    }
    void setMarksCount(int count)
    {
        marksCount = count;
    }

    static void printMarks(Student* s1)
    {
        for (int i = 0; i < s1->getMarksCount(); i++)
        {
            cout << s1->getMarks()[i];
        }
    }
};

int main()
{
const int SIZE = 5;
int* marks1 = new int[SIZE] { 2, 3, 5, 4, 1 };
int* marks2 = new int[SIZE] { 4, 2, 3, 1, 2 };

Student* s1 = new Student(marks1, SIZE);
Student* s2 = new Student(marks2, SIZE);

Student* s = s1 + s2;


Student::printMarks(s1);
}

您不需要在此处使用 new 或指针

Student* s1 = new Student(marks1, SIZE);
Student* s2 = new Student(marks2, SIZE);

Student* s = s1 + s2;

所以改为

Student s1{marks1, SIZE};
Student s2{marks2, SIZE};

Student s = s1 + s2;

同样,我会将您所有的 int* 更改为 std::vector<int>,并基本上删除整个代码中的所有 new 调用。