[在C ++中使用带字符串的复制构造函数和/或赋值运算符时的堆栈溢出

问题描述 投票:0回答:1

我试图在我自己制作的简单类上运行插入排序,该类具有几个字段(int,float和string)以及复制构造函数,赋值运算符和'>'运算符。

但是,当我运行下面的代码时,我得到了堆栈溢出。 visual studio告诉我它来自我的“学生”类中的getName()函数。错误源自我的插入排序函数arr[i + 1] = arr[i];中的赋值]

有人知道这是为什么吗?我对c ++比较陌生,主要来自Java背景。

#include <iostream>
#include <vector>
#include <string>
using namespace std;

class Student {
public:
    Student(string nm, int ID, float avg): name(nm), studentID(ID), overallAverage(avg) {}

    Student(const Student& rhs) : name(rhs.getName()), studentID(rhs.getStudentID()), overallAverage(rhs.getOverallAverage()) {}

    // copy and swap idiom
    Student& operator=(const Student& rhs) {
        Student copy = rhs;  // places a copy of rhs into copy using the copy constructor (copy will be cleaned up on return)
        swap(*this, copy); // move copy or rhs into this, this is a pointer to current object, *this dereferences the pointer
        return *this; 
    }
    ~Student() {}

    bool operator>(const Student& rhs) {
        if (rhs.getOverallAverage() > overallAverage)
            return false;
        else return true; 
    }

    string getName()const { return name; }
    int getStudentID()const { return studentID;  }
    float getOverallAverage()const { return overallAverage; }

private:
    string name; 
    int studentID; 
    float overallAverage; 

};

template<typename T> 
vector<T>& insertionSort(vector<T>& arr){
    for (int j = 1; j < arr.size(); j++) {
        T key = arr[j]; 
        int i = j - 1; 
        while (i > -1 && arr[i] > key) {
            arr[i + 1] = arr[i]; 
            i = i - 1; 
        }
        arr[i + 1] = key; 
    }
    return arr; 
}


int main()
{
    vector<Student> students = {Student("russ",0,89),Student("Seb",1,75),Student("julia",2,85),
                                Student("johnny",3,90),Student("Sushma",4,55)}; 

    students = insertionSort(students); 

    for (int i = 0; i < students.size(); i++) {
        cout << students[i].getName() << ", ";
    }
    cout << endl;  
}

原始操作员=来自我正在使用的txtbook:

IntCell & operator= ( const IntCell & rhs ) // Copy assignment
{
IntCell copy = rhs;
std::swap( *this, copy );
return *this;
}

我试图在我自己制作的简单类上运行插入排序,该类具有几个字段(int,float和string)以及复制构造函数,赋值运算符和'>'运算符。 ...

c++ c++11 stack-overflow copy-constructor assignment-operator
1个回答
1
投票

无限递归是由std::swap调用Student::operator=,调用std::swap,调用Student::operator=等引起的>

为减轻这种情况,编写您自己的swap函数,该函数在每个成员上调用std::swap

© www.soinside.com 2019 - 2024. All rights reserved.