0

我正在创建一个函数,当我的 Student 类中的两个对象被重载时,它会重载 + 运算符。该函数应该添加他们的年龄和身高(类的两个受保护的数据字段)。然后它调用构造函数来创建一个具有这些字段的新学生。这也是模板中的练习,因此无法删除这些字段。

当我编译我的程序时,我在运行时遇到了分段错误。使用 cout 语句,我可以看到正在创建新的 Student 并且退出了构造函数,但是随后发生了分段错误。我意识到这一定是内存问题,但我无法找到解决方案。我尝试使用动态内存在重载运算符和主函数中创建新学生,但错误仍然存​​在。

这是构造函数:

template <typename T>
Student<T>::Student(int age, int height)
{
    this->age = age;
    this->height = height;

    cout << "New student created"<< endl;
    return;
}  

这是重载的运算符函数:

template<typename T>
Student<T> Student<T>::operator+(Student<T> &secondStudent) const
{
    int a = age + secondStudent.getAge();
    int h = height + secondStudent.getHeight();

    new Student(a, h);
}

这是主要功能:

Student<int> *s2 = new Student<int>(15, 63);
Student<int> *s3 = new Student<int>(18, 72);

Student <int> s4 = (*s2+ *s3);
cout << "did it return?" << endl;

注意这两个 cout 语句是打印的,所以我知道调用了操作符并创建了学生,但是随后遇到了内存问题。

4

2 回答 2

2

您的operator +重载不会返回任何内容(您没有return声明),因此您会遇到未定义的行为(导致分段错误的原因)。此外,您的operator +函数通过忽略new. 甚至没有理由在new这里使用。你想说:

template<typename T>
Student<T> Student<T>::operator+(Student<T> &secondStudent) const
{
    int a = age + secondStudent.getAge();
    int h = height + secondStudent.getHeight();

    return Student(a, h);
}

你不需要new在 C++ 中使用关键字,除非你有特定的理由在堆上分配一些东西。(new返回一个指向动态分配对象的指针。)在您的情况下,您只想创建并返回一个Student对象。

于 2013-04-26T18:42:49.093 回答
2

问题在这里:

template<typename T>
Student<T> Student<T>::operator+(Student<T> &secondStudent) const
{
    int a = age + secondStudent.getAge();
    int h = height + secondStudent.getHeight();

    new Student(a, h);
//  ^^^^^^^^^^^^^^^^^^
}

您正在动态创建一个对象,但您的函数中没有return声明。这是未定义的行为(此外,您还泄漏了该对象,因为没有相应的调用delete)。相反,你可以写:

template<typename T>
Student<T> Student<T>::operator+(Student<T> &secondStudent) const
{
    int a = age + secondStudent.getAge();
    int h = height + secondStudent.getHeight();

    return Student(a, h);
//  ^^^^^^^^^^^^^^^^^^^^^
}

请注意,通过原始指针、new和手动管理内存delete通常是一个坏主意。如果您确实需要引用语义,请考虑使用智能指针。

于 2013-04-26T18:43:17.807 回答