1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
|
#ifndef STUDENT_H
#define STUDENT_H
#include <vector>
class Student
{
public:
Student(int, std::vector<int> grades);
Student(Student& other);
~Student( );
Student& operator=(Student& other);
void swap(Student& other) throw( );
bool operator==(const Student& other) const;
void setGrades(int);
int getGrades(int);
int getNumOfStudents( );
void setNumOfStudents(int);
int getHistogram(int);
void setHistogram(int, int);
private:
std::vector<int> _grades;
int _numOfStudents;
int *_pHistogram;
};
#endif // STUDENT_H
#include "student.h"
#include <vector>
#include <string.h>
Student::Student(int numOf, std::vector<int> grades) //<======= Tested
{
_numOfStudents = numOf;
_pHistogram = new int[numOf];
_grades = grades;
}
Student::Student(Student& other) //<======Tested
{
this->_numOfStudents = other._numOfStudents;
memcpy ( &this->_grades, &other._grades, sizeof(int));
memcpy ( &this->_pHistogram, &other._pHistogram, sizeof(int)); //<== segmentation fault
}
Student::~Student()
{
delete [] _pHistogram;
}
Student& Student::operator=(Student& other)
{
other.swap(*this);
return *this;
}
void Student::swap(Student& other) throw( )
{
std::swap(_grades, other._grades);
std::swap(_numOfStudents, other._numOfStudents);
std::swap(_pHistogram, other._pHistogram);
}
bool Student::operator==(const Student& other) const
{
return true;
}
void Student::setGrades(int grade) //<======= Tested
{
_grades.push_back(grade);
}
int Student::getGrades(int index) //<======= Tested
{
return _grades[index];
}
int Student::getNumOfStudents( ) //<======= Tested
{
return _numOfStudents;
}
void Student::setNumOfStudents(int numOf)
{
_numOfStudents = numOf;
}
int Student::getHistogram(int index)
{
return _pHistogram[index];
}
void Student::setHistogram(int index, int histo)
{
_pHistogram[index] = histo;
}
#include <iostream>
#include <vector>
#include "student.h"
int main(int argc, char **argv)
{
std::vector<int> grades;
Student test(10, grades);
int grade =0, index =0;
while (grade != -1)
{
std::cout << "Enter a grade:(-1 to exit): ";
std::cin >> grade;
test.setGrades(grade);
index++;
}
Student cpyTest = test;
// Student cpyTest2(test);
// for (int i =0; i < cpyTest.getNumOfStudents(); i++)
// {
// std::cout << cpyTest.getGrades(i) << std::endl;
//
// }
// std::cout << "Test2" << std::endl;
// for (int i =0; i < cpyTest2.getNumOfStudents(); i++)
// {
// std::cout << cpyTest2.getGrades(i) << std::endl;
//
// }
return 0;
|