table.h
#pragma once#include <iostream>#include "Student.h"#include <vector>using namespace std;class table{ // Private class variables string staff; int numSeats; vector<Student> seating;public: table(); // Default constructor table(string s,int n); table(const table& that) : staff(that.staff),numSeats(that.numSeats) { } // copy Constructor table& operator=(const table& that) { staff = that.staff; numSeats = that.numSeats; return *this; } int getNumSeats(); string getStaffname(); voID addStudent(Student student); voID removeStudent(Student student); voID clearStudents(); vector<Student> gettableSeating(); int getRemainingSeats(); ~table(voID);};
这是学生班级文件:
#pragma once#include <iostream>#include <vector>using namespace std;class Student{ string name; string country; vector<int> tablesSatAt;public: Student(string n,string c); Student(); Student(const Student& that) : name(that.name),country(that.country) { } Student& operator=(const Student& that) { name = that.name; country = that.country; return *this; } string getname(); string getCountry(); voID addtable(int tableNumber); voID removetable(int tableNumber); bool satAttable(int tableNumber); frIEnd bool operator==(Student s1,Student s2); frIEnd bool operator!=(Student s1,Student s2); ~Student(voID);};bool operator==(Student s1,Student s2);bool operator!=(Student s1,Student s2);
这是执行繁重工作的递归函数:
bool seatRecursive(vector<Student> &tempStudents,vector<table> &temptables){ if (tempStudents.size() == 0) return true; //base case Student nextStudent = randomSelect(tempStudents); for (vector<int>::size_type i=0; i<temptables.size(); i++) { if (temptables[i].getRemainingSeats() > 0 && !nextStudent.satAttable(i)) { addStudentTotable(nextStudent,temptables,i); if (seatRecursive(tempStudents,temptables)) return true; else { removeStudentFromtable(nextStudent,i); tempStudents.push_back(nextStudent); } } } return false;}
大部分都有效.当我运行该程序时,我得到一个有10周座位的文本文件,但所有桌面座位都是相同的.即如果我是一名特定的工作人员,我有同样的孩子在我的餐桌上待了整整10个星期.我有一个int的向量,应该存储学生随时间坐着的表号.在调试时,我注意到那些表号不存储在该向量中,它总是空的.我的问题是,我无法弄清楚为什么会这样.是因为我通过引用传递向量吗?是否与指针有关,即使我没有明确声明指针?
非常感谢任何建议,如有必要,我可以粘贴其余的代码.
布赖恩
解决方法 我看到Student和table类的复制构造函数(和赋值构造函数)忘记了复制包含的STL向量(向量< Student> seat和vector< int> tablesSatAt).由于重载这些构造函数,您应该通过向量复制构造函数复制它们,因为它不是隐式完成的.在不复制它们的情况下,每当学生或表围绕向量移动(或分配给临时)时,内部向量将被丢弃以用于新对象.
正如Useless在这种情况下的评论所指出的,你不需要声明它们,因为rule of three不适用:你不需要析构函数,所以你可能不需要两个拷贝构造函数.
注意:您在注释中称为复制构造函数的是复制赋值构造函数.之前的一个是真正的拷贝构造函数.
总结以上是内存溢出为你收集整理的C类问题全部内容,希望文章能够帮你解决C类问题所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)