c++ - 通过引用将派生类传递给运算符会产生错误
问题描述
我正在尝试实现来自抽象类的派生类。我通过引用将派生类传递给函数,然后调用在父抽象类中实现的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)
解决方案
显然我犯了一个错误,没有在set_name()
函数中返回任何字符串值。它适用于某些编译器,但不适用于我的。所以我改为string set_name()
并且void set_name()
它有效。比你们所有人的帮助!
推荐阅读
- omnet++ - 错误:语法错误,意外名称,在 OMNET++ 中期望 $end?
- python - 如何计算csv文件中每天的条目?
- python - 不同参数的Python烧瓶蓝图注册路线
- android - 是否可以在 android 上将 node js 应用程序作为后台服务运行?
- c++ - 未使用附加字段调用凭据提供程序“SetComboBoxSelectedValue”
- c++ - 无法将来自外部共享库的信号连接到 QWidget 派生类的重载插槽
- c# - EPERM:不允许操作 - IIS 上的 NPM Angular 7 与后端 .Net Core 2.1
- mysql - 使用大小写按计算列过滤和排序(未找到列)
- apache-kafka - 如果kafka文件被删除会怎样?
- shell - 如何将别名翻译成真实文件?