我正在尝试实现来自抽象类的派生类。我通过引用将派生类传递给函数,然后调用在父抽象类中实现的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():无效的大小
以退出代码134(被信号6:SIGABRT中断)结束的过程
答案 0 :(得分:0)
很显然,我在set_name()
函数中未返回任何字符串值而犯了一个错误。它适用于某些编译器,但不适用于我的。因此,我将string set_name()
更改为void set_name()
,它可以正常工作。比大家的帮助!