I am writing c++ program.
This is snippet of main method:
Student * array = new Student[4];
int i = 0;
for(char x = 'a'; x < 'e'; x++){
array[i] = new Student(x+" Bill Gates");
i++;
}
defaultObject.addition(array, 4);
This line array[i] = new Student(x+" Bill Gates"); throws an error:
g++ -c -g -MMD -MP -MF build/Debug/Cygwin-Windows/Run.o.d -o build/Debug/Cygwin-Windows/Run.o Run.cpp
In file included from Run.cpp:12:
Assessment3.hpp:53:39: warning: no newline at end of file
Run.cpp: In function `int main(int, char**)':
Run.cpp:68: error: no match for 'operator=' in '*((+(((unsigned int)i) * 8u)) + array) = (string(((+((unsigned int)x)) + ((const char*)" Bill Gates")), ((const std::allocator<char>&)((const std::allocator<char>*)(&allocator<char>())))), (((Student*)operator new(8u)), (<anonymous>->Student::Student(<anonymous>), <anonymous>)))'
Student.hpp:19: note: candidates are: Student& Student::operator=(Student&)
make[2]: Leaving directory `/cygdrive/g/Aristotelis/C++/assessment3'
make[1]: Leaving directory `/cygdrive/g/Aristotelis/C++/assessment3'
make[2]: *** [build/Debug/Cygwin-Windows/Run.o] Error 1
make[1]: *** [.build-conf] Error 2
make: *** [.build-impl] Error 2
BUILD FAILED (exit value 2, total time: 3s)
Student class is over here:
#include "Student.hpp"
#include <string>
using namespace std;
Student::Student(){
in = "hooray";
}
Student::Student(string in) {
this -> in = in;
}
Student::Student(const Student& orig) {
}
Student::~Student() {
}
Student & Student::operator=(Student & student){
if(this != &student){
this->in = student.in;
}
return *this;
}
Header file is here:
#include <string>
using namespace std;
#ifndef STUDENT_HPP
#define STUDENT_HPP
class Student {
public:
Student();
Student(string in);
Student(const Student& orig);
virtual ~Student();
Student & operator=(Student & student); // overloads = operator
private:
string in;
};
#endif /* STUDENT_HPP */
This part of program creates array of type Student and stores objects of type student. The the array is passed to compare the values according to bubble sort. What might be the problem?
‘array’ is an array of students declared on the freestore not of array of pointers to students so you can’t assign a pointer to them, new returns a pointer to a new location on the freestore. Instead you assign a student to the indexed location.
Also whilst I am here, you can’t concatenate a C string and a char like that. You can however use a std::string to do that heavy lifting.
Finally, you will save a lot of time, if you a vector instead a C array, a vector will manage it’s own memory and provides a interface for you to use.
Vectors and string are the defacto way of dealing with arrays and string in c++.