首页 > 解决方案 > 通过引用将派生类传递给运算符会产生错误

问题描述

我正在尝试实现来自抽象类的派生类。我通过引用将派生类传递给函数,然后调用在父抽象类中实现的setter。这给了我记忆错误。我试图用更简单的代码来说明这个问题,但是我没有实现它,所以我想再做一次:D

#include <iostream>
#include <string>
#include <vector>

using namespace std;

class Person {
private:
    string name;
    string lastname;
public:
    string get_name() const { return name; };
    string get_lastname() const { return lastname; };
    string set_name(string s) { name = s; };
    string set_lastname(string s) { lastname = s; };

    virtual void get_title() = 0;

    Person() { };
    Person(string name_set, string lastname_set): name(std::move(name_set)), lastname(std::move(lastname_set)) {};
};

class Student : public Person {
private:
    vector<double > marks;
    int exam;
public:
    Student() {};
    Student(string name_set, string lastname_set):Person(name_set, lastname_set) {};
    void get_title() { cout  << "This is a student\n"; };
    void set_mark(double mark_set) { marks.push_back(mark_set); };
    void set_exam(int exam_set) { exam = exam_set; };
    double get_final() const;
    double get_final_median();
    friend bool operator > (const Student &a, const Student &b) { return a.get_final() > b.get_final(); }
    friend bool operator < (const Student &a, const Student &b) { return a.get_final() < b.get_final(); }
    friend bool operator == (const Student &a, const Student &b) { return a.get_final() == b.get_final(); }
    friend bool operator != (const Student &a, const Student &b) { return a.get_final() != b.get_final(); }

    friend std::istream & operator >> (std::istream & in, Student & a) {
        int marks;
        int val;
        string st;
        std::cout << "Enter student's name: ";
        in >> st;
        // THIS PART GIVES ME AN ERROR
        a.set_name(st);
        std::cout << "And last name: ";
        in >> st;
        a.set_lastname(st);
        std::cout << "Enter marks count: ";
        in >> marks;
        for (int i = 0; i < marks; i++) {
            std::cout << "Enter mark: ";
            in >> val;
            if (val < 1 || val > 10) {
                std::cout << "Bad value";
                i--;
                continue;
            }
            a.marks.push_back(val);
        }
        std::cout << "Enter exam result: ";
        in >> val;
        if (val < 1 || val > 10) a.exam = 1;
        else a.exam = val;
        return in;
    }
};

int main() {
    Student c;
    // Error part
    cin >> c;
    return 0;
}

我得到的错误是: free(): invalid size

进程以退出代码 134 结束(被信号 6 中断:SIGABRT)

标签: c++

解决方案


显然我犯了一个错误,没有在set_name()函数中返回任何字符串值。它适用于某些编译器,但不适用于我的。所以我改为string set_name()并且void set_name()它有效。比你们所有人的帮助!


推荐阅读