double mean(vector<Reading> temps)
{
// stub version
double mean_temp;
double sum = 0;
for (int i = 0; i< temps.size(); ++i) sum += temps[i];
mean_temp = sum/temps.size();
return (mean_temp);
}
double median(vector<Reading> temps)
{
// stub version
double median_temp;
sort (temps.begin(), temps.end());
median_temp = temps[temps.size()/2];
return (median_temp);
}
============================================
Result in errors:
proj4.cc: In function ‘double mean(Vector<Reading>)’:
proj4.cc:132: error: no match for ‘operator+=’ in ‘sum += temps.Vector<T>::operator[] [with T = Reading](((unsigned int)i))’
proj4.cc: In function ‘double median(Vector<Reading>)’:
proj4.cc:142: error: cannot convert ‘Reading’ to ‘double’ in assignment
=============================================
Full code below. I need to tackle these two errors before I can proceed
#include <bjarne/std_lib_facilities.h>
struct Reading {
int hour;
double temperature;
Reading(int h, double t): hour(h), temperature(t) { }
bool operator<(const Reading &r) const;
};
bool Reading::operator<(const Reading &r) const
{
// stub version
vector<Reading> temps;
sort (temps.begin(), temps.end());
}
/*
* function declarations
*/
ostream& operator<<(ostream& ost, const Reading &r);
vector<Reading> get_temps();
double check_adjust_temp(double temperature, char scale);
double c_to_f(double temperature);
double mean(vector<Reading> temps);
double median(vector<Reading> temps);
void print_results(const vector<Reading>& temps, double mean_temp,
double median_temp);
int main()
try
{
vector<Reading> temps = get_temps();
if (temps.size() == 0) error("no temperatures given!");
double mean_temp = mean(temps);
sort(temps.begin(), temps.end());
double median_temp = median(temps);
print_results(temps, mean_temp, median_temp);
}
catch (exception& e) {
cerr << "error: " << e.what() << '\n';
return 1;
}
catch (...) {
cerr << "Oops: unknown exception!\n";
return 2;
}
/*
* function definitions
*/
ostream& operator<<(ostream& ost, const Reading &r)
{
// stub version
/*
*/
return ost;
}
vector<Reading> get_temps()
{
// stub version
cout << "Please enter name of input file name: ";
string name;
cin >> name;
ifstream ist(name.c_str());
if(!ist) error("can't open input file ", name);
vector<Reading> temps;
int hour;
double temperature;
while (ist >> hour >> temperature){
if (hour <0 || 23 <hour) error("hour out of range");
temps.push_back( Reading(hour,temperature));
}
}
double check_adjust_temp(double temperature, char scale)
{
// stub version
if (scale== 'c' || 'C'){
return c_to_f(temperature);
}
else if (scale== 'f' || 'F') {
return temperature;
}
else {
error("Wrong input type");
}
}
double c_to_f(double temperature)
{
// stub version
double c;
c = ((temperature * (9.0/5)) + 32);
return (c);
}
double mean(vector<Reading> temps)
{
// stub version
double mean_temp;
double sum = 0;
for (int i = 0; i< temps.size(); ++i) sum += temps[i];
mean_temp = sum/temps.size();
return (mean_temp);
}
double median(vector<Reading> temps)
{
// stub version
double median_temp;
sort (temps.begin(), temps.end());
median_temp = temps[temps.size()/2];
return (median_temp);
}
void print_results(const vector<Reading>& temps, double mean_temp,
double median_temp)
{
// stub version
cout << "The sorted temperatures are:\n";
cout << get_temps;
cout << "The mean temperature is " << mean_temp << ".\n";
cout << "The median temperature is " << median_temp << ".\n";
}
Define a conversion operator for Reading:
struct Reading {
int hour;
double temperature;
Reading(int h, double t): hour(h), temperature(t) { }
bool operator<(const Reading &r) const;
operator double() { return temperature; }
};
Or, better (via the Principle of Least Astonishment), just change the usage of your class:
// was:
sum += temps[i];
//change to:
sum += temps[i].temperature;
// was:
median_temp = temps[temps.size()/2];
//change to:
median_temp = temps[temps.size()/2].temperature;
You're trying to execute an addition between an instance of a class Reading and a double. This doesn't work as long as you don't provide either a default conversion path from Reading to double:
Reading::operator double() const { return temperature; }
or by providing proper global operator+() overloads:
double operator+(Reading const&, double);
double operator+(double, Reading const&);
The second error should be solvable with the Reading::operator double() as shown above.
You are missing operator+= for the class Reading
you are trying to sum up Reading objects into a double variable!
sum += temps[i];
sum type is double while temps[i] returns Reading object, you cannot sum double and Reading object since they belong to different types, you must define an overload of plus operator and make the compiler understand how this is done.
Related
Sorry for variables not being all in engilsh. I have a problem when i try to do the += operation on class called Uklad3.
It is initialized the same way as previous ones, but with this one the segmentation failure comes up when i try to do any operations on it.
Any sugestions how to fix it? I am not a proffesional programmer.
I sumbited the whole code because I know it might be little hard to read, I am learning and this is for ma class.
The goal of the operation += is to add points from one coordinate system to the other. It is only the portion of the task but this is where I have a problem.
class punkt
{
private:
double x;
double y;
double z;
public:
punkt(){};
string name;
punkt(string,double,double,double);
double getx() const {return x;}
double gety() const {return y;}
double getz() const {return z;}
};
punkt::punkt(string name_,double x_, double y_, double z_)
{
name=name_;
x=x_;
y=y_;
z=z_;
}
class Uklad
{
public:
static const int size = 10;
punkt tablica[size];
string uklad_name;
void add(punkt);
int licznik;
Uklad(){licznik=0;};
Uklad(string);
Uklad & operator+=(const Uklad &var)
{
for(int i=0;i<var.licznik;i++)
{
tablica[licznik]=var.tablica[i];
licznik++;
}
}
Uklad & operator-= (const Uklad &var)
{
for(int i=0;i<licznik;i++)
{
for(int j=0;j<var.licznik;j++)
{
if((tablica[i].getx()==var.tablica[i].getx()) and (tablica[i].gety()==var.tablica[i].gety()) and (tablica[i].getz()==var.tablica[i].getz()))
{
for(int k=i;k<licznik;k++)
{
tablica[k]=tablica[k+1];
}
licznik--;
}
}
}
}
};
Uklad::Uklad(string uklad_name_)
{
uklad_name=uklad_name_;
cout<<"Tworze uklad"<<endl;
}
void Uklad::add(punkt toAdd)
{
if(licznik<size)
{
tablica[licznik]=toAdd;
licznik++;
}
}
}
ostream & operator<<(ostream &s, const punkt &Punkt)
{
cout<<Punkt.name<<" "<<Punkt.getx()<<" "<<Punkt.gety()<<" "<<Punkt.getz();
return s<<" ";
}
ostream & operator<<(ostream &s, const Uklad &uklad)
{
for(int i=0;i<uklad.licznik;i++)
{
if(i==uklad.licznik-1) cout<<uklad.tablica[i]<<" ";
else
cout<<uklad.tablica[i]<<"; ";
}
return s<<" ";
}
int main()
{
//1.
string name1,name2,name3;
cin>>name1;
cin>>name2;
Uklad uklad1(name1);
Uklad uklad2(name2);
//2.
const int M=2;
double xtemp, ytemp, ztemp;
string nametemp;
string xs,ys,zs;
for(int i=0;i<M;i++)
{
cin>>nametemp;
cin>>xtemp;
cin>>ytemp;
cin>>ztemp;
punkt punktT(nametemp,xtemp,ytemp,ztemp);
uklad1.add(punktT);
}
//3.
const int N=2;
double xtemp2, ytemp2, ztemp2;
string nametemp2;
string xs2,ys2,zs2;
for(int i=0;i<N;i++)
{
cin>>nametemp2;
cin>>xtemp2;
cin>>ytemp2;
cin>>ztemp2;
punkt punktT2(nametemp2,xtemp2,ytemp2,ztemp2);
uklad2.add(punktT2);
}
//4.
cin>>name3;
Uklad uklad3(name3);
//5.
uklad3+=uklad1;
cout<<uklad3;
return 0;
}
static const int size = 10;
You make array about 10 size and after all this loops you go out of range of the array. That's why you have this error. You can give it higher size. Or you can use vectors. In case of using array you must be sure you will not go out of range.
I formated the code and add initializer to licznik. This code haven't segmentation fault error
class punkt
{
private:
double x;
double y;
double z;
public:
punkt(){};
string name;
punkt(string,double,double,double);
double getx() const {return x;}
double gety() const {return y;}
double getz() const {return z;}
};
punkt::punkt(string name_,double x_, double y_, double z_)
{
name=name_;
x=x_;
y=y_;
z=z_;
}
class Uklad
{
public:
static const int size = 10;
punkt tablica[size];
string uklad_name = "";
void add(punkt);
int licznik = 0;
Uklad(){licznik=0;};
Uklad(string);
Uklad& operator+=(const Uklad &var)
{
for(int i=0;i<var.licznik;i++)
{
cout << licznik << " += ";
tablica[licznik]=var.tablica[i];
licznik++;
}
return *this;
}
Uklad & operator-= (const Uklad &var)
{
for(int i=0;i<licznik;i++)
{
for(int j=0;j<var.licznik;j++)
{
cout << i << " -=";
if((tablica[i].getx()==var.tablica[i].getx()) and (tablica[i].gety()==var.tablica[i].gety()) and (tablica[i].getz()==var.tablica[i].getz()))
{
for(int k=i;k<licznik;k++)
{
tablica[k]=tablica[k+1];
}
licznik--;
}
}
}
return *this;
}
};
Uklad::Uklad(string uklad_name_)
{
licznik = 0;
uklad_name=uklad_name_;
cout << "Tworze uklad" << endl;
}
void Uklad::add(punkt toAdd)
{
if(licznik<size)
{
tablica[licznik]=toAdd;
licznik++;
}
}
ostream & operator<<(ostream &s, const punkt &Punkt)
{
cout<<Punkt.name<<" "<<Punkt.getx()<<" "<<Punkt.gety()<<" "<<Punkt.getz();
return s<<" ";
}
ostream & operator<<(ostream &s, const Uklad &uklad)
{
for(int i=0;i<uklad.licznik;i++)
{
if(i==uklad.licznik-1) cout<<uklad.tablica[i]<<" ";
else
cout<<uklad.tablica[i]<<"; ";
}
return s<<" ";
}
int main()
{
//1.
string name1,name2,name3;
cin>>name1;
cin>>name2;
Uklad uklad1(name1);
Uklad uklad2(name2);
//2.
const int M=2;
double xtemp, ytemp, ztemp;
string nametemp;
string xs,ys,zs;
for(int i=0;i<M;i++)
{
cin>>nametemp;
cin>>xtemp;
cin>>ytemp;
cin>>ztemp;
punkt punktT(nametemp,xtemp,ytemp,ztemp);
uklad1.add(punktT);
}
//3.
const int N=2;
double xtemp2, ytemp2, ztemp2;
string nametemp2;
string xs2,ys2,zs2;
for(int i=0;i<N;i++)
{
cin>>nametemp2;
cin>>xtemp2;
cin>>ytemp2;
cin>>ztemp2;
punkt punktT2(nametemp2,xtemp2,ytemp2,ztemp2);
uklad2.add(punktT2);
}
//4.
cin>>name3;
Uklad uklad3(name3);
//5.
uklad3+=uklad1;
cout<<uklad3;
return 0;
}
I've been looking around to see if anyone has a similar issue to me and i couldn't find anything. I am prompting the user to type in the name of the planet they wish to delete. My function will locate the position of the planet within the vector objects.
The purpose of this function is to delete a object based on the position i pass through the function parameters.
Planet Class
class Planet {
private:
string name;
double diameter;
double mass;
public:
const double G = 6.67408e-11;
void setName(string n);
bool setDiameter(double d);
bool setMass(double m);
string getName();
double getDiameter();
double getMass();
double CalcSa();
double CalcV();
double CalcDensity();
double CalcG();
string InputS(string x);
double InputD(string x);
Planet();
};
double ReadDouble(double input) {
//Verifys that that user entered in a correct number
while (cin.fail() != 0) {
cerr << "Enter a valid number: ";
cin.clear();
cin.ignore(255, '\n');
cin >> input;
}
return input;
}
string Planet::InputS(string x) {
string user_input;
cout << x;
cin >> user_input;
return user_input;
}
double Planet::InputD(string x) {
double user_input;
cout << x;
cin >> user_input;
user_input = ReadDouble(user_input);
return user_input;
}
Planet::Planet() {
name;
diameter = 0.0;
mass = 0.0;
}
void Planet::setName(string n) {
name = n;
}
bool Planet::setDiameter(double d) {
bool rv = false;
if (d > 0.0) {
rv = true;
diameter = d;
}
return rv;
}
bool Planet::setMass(double m) {
bool rv = false;
if (m > 0.0) {
rv = true;
mass = m;
}
return rv;
}
string Planet::getName() {
return name;
}
double Planet::getMass() {
return mass;
}
double Planet::getDiameter() {
return diameter;
}
double Planet::CalcSa() {
double sa = 4.0 * M_PI * pow((diameter / 2.0), 2.0);
return sa;
}
double Planet::CalcV() {
double v = (4.0 / 3.0) * M_PI * pow((diameter / 2.0), 3.0);
return v;
}
double Planet::CalcDensity() {
double den = mass / CalcV();
return den;
}
double Planet::CalcG() {
double r = diameter / 2.0;
double grav = (G * mass) / (pow(r, 2.0));
return grav;
}
My issue is with this line of code:
l.erase(l.begin() + n);
void DeleteVector(vector<Planet>& l, int n) {
if (int len = l.size() > 0) {
cout << l[n].getName() << " was removed from the list.\n";
l.erase(l.begin() + n);
}
}
i pass in the vector of planets which is a class. and then i pass in the position "n" which i wish to remove from the vector of objects.
I get the following error:
Error C2280 'Planet &Planet::operator =(const Planet &)': attempting to reference a deleted function
Any help or guidance would be appreciated.
The copy assignment operator for your class Planet is implicitly deleted by your compiler, because it has a const member.
See Deleted implicitly-declared copy assignment operator:
A defaulted copy assignment operator for class T is defined as deleted if any of the following is true:
T has a non-static data member of non-class type (or array thereof) that is const;
You probably meant G to be static const:
static const double G;
and then outside of your class:
const double Planet::G = 6.67408e-11;
I am trying to learn how to use c++11 user defined literals for units of physical properties. The question is, how do I avoid a mixing of these units. So that (8.0_kg + 8.0_km)--> gives error. any ideas guys? i am new to c++, be kind.
class Mass{
public:
//Mass(){
// cout << "only Mass units allowed in here" << endl;
//}
//~Mass();
long double getWeight(long double a);
double car, house, cat;
private:
long double a;
};
long double Mass::getWeight(long double w) {
cout << "returning argument: " << w << '\n'<< endl;
return 0;
}
long double operator"" _km(long double d) { return d * 1000.0; }
long double operator"" _m (long double d) {return d;}
long double operator"" _cm(long double d) { return d / 100.0; }
long double operator"" _tonne(long double m) { return m * 1000.0 ; }
long double operator"" _kg(long double m) { return m ; }
long double operator"" _lb(long double m) { return m * 0.453592; }
long double getDistance(long double d){
long double starting_d = 61.0_kg;
long double total_d = d + starting_d;
cout << "the distance I have run is: " << total_d << endl;
return 0;
}
int main() {
cout << 6.0_km << endl;
cout << 6.0_km + 3.0_m << endl;
cout << 6.0_km + 3.0_m + 15.0_cm << '\n' << endl;
cout << 8.0_tonne << endl;
cout << 8.0_km + 4.0_kg << endl;
cout << 8.0_km + 4.0_kg + 21.0_lb << '\n' << endl;
long double distance = 5.45_km;
getDistance(distance);
Mass obj1;
obj1.getWeight(13.96_lb);
cout << "This is clearly wrong: "<< 8.0_km + 4.0_kg << endl;
obj1.getWeight(10.96_km); // so is this
}
You need to define your own types, since you can't restrict what a primitive represents.
You can use a "tagged template"1 to avoid repetition of operators and such and keep it type safe.
This can be extended so you get for instance distance * distance = area or speed * time = distance checked by the compiler.
Here's a short example:
template<typename Kind>
struct Value
{
long double value;
Value& operator+= (Value v) { value += v.value; return *this; }
};
template <typename Kind>
Value<Kind> operator+ (Value<Kind> lhs, Value<Kind> rhs) { return lhs += rhs; }
// These types don't need definitions; we only need some unique type names.
struct M;
struct D;
using Mass = Value<M>;
using Distance = Value<D>;
Mass operator"" _kg(long double d) { return { d };}
Mass operator"" _lb(long double d) { return { d * 0.453592 };}
Distance operator"" _km(long double d) { return { d * 1000 };}
Distance operator"" _mile(long double d) { return { d * 1609 };}
int main()
{
// OK
Distance d = 1.2_km + 0.2_mile;
// OK
Mass m = 2.3_kg + 1.4_lb;
// invalid operands to binary expression ('Distance' (aka 'Value<D>')
// and 'Mass' (aka 'Value<M>'))
Distance d2 = 2.4_km + 1.2_kg; // Nope
}
1) I don't think there's an established term in C++, but it's very similar to what Haskell refers to as phantom types.
Create classes representing numeric values of the different units. That's how it's been done since long before C++ 11.
Custom literals can make instantiation more readable, though, because it helps preserve the usual order of number and unit :)
See http://en.cppreference.com/w/cpp/language/user_literal
class MassKg
{
double value;
// public c'tor, numeric operators, &c.
};
// ...
MassKg mass(5.0);
DistanceM distance(3.0);
auto c = mass * distance; // may yield an instance of TorqueKgM, or MomentumKgM, therefore
// explicit functions / methods are preferrable for mixed
// multiplication or division
auto mass2 = mass + MassKg(2.0); // yiels an instance of MassKg
auto invalid = mass + distance; // compile time error
I have modified both the user defined classes to have constructors that accepts an object of the other class as it's argument.
Does this cover all the bases or do I have to overload the assignment operator and the type-cast operator as well to handle all the implicit and explicit type casting cases?
Eg:
#include <iostream>
using namespace std;
class Celsius; // Forward Declaration
class Fahrenheit {
double temp;
public:
Fahrenheit(double d = 0.0) : temp(d) {}
Fahrenheit(Celsius);
void setTemp(double d) { temp = d; }
double getTemp() { return temp; }
void print() { cout << "\nThe temperature value in Fahrenheit is " << temp << endl; }
};
class Celsius {
double temp;
public:
Celsius(double d = 0.0) : temp(d) {}
Celsius(Fahrenheit f) { temp = ((f.getTemp()-32) * 5) / 9; }
void setTemp(double d) { temp = d; }
double getTemp() { return temp; }
void print() { cout << "\nThe temperature value in Celsius is " << temp << endl; }
};
Fahrenheit::Fahrenheit(Celsius c) { temp = ((c.getTemp() * 9) / 5) + 32; }
int main() {
Fahrenheit t1(20);
Celsius t2(t1);
Fahrenheit t3(50);
t2.print();
t2 = (Celsius) t3;
t2.print();
cin.get();
return 0;
}
I have an array of objects which all derive from the class BaseStudent.
BaseStudent**studentlist = new BaseStudent*[atoi(listSize.c_str())];
That array is populated with either derived Math, English or History objects. I'm now trying to print out specific data from each object in the array and output it to a file.
for (int j=0; j<atoi(listSize.c_str()); j++){
if(studentlist[j]->getMT() == ENGLISH){
output << studentlist[j]->GetFN()<<" "<<studentlist[j]->GetLN();
output << right << setw(42) << studentlist[j]->GetFinal(); // this is an English public function but I can't call this.
}
}
I need to be able to access the derived classes private member data from the array of objects.
Here's my header. As you can see I have a setter and getter for every protected member data.
#include <iostream>
#include <string>
using namespace std;
#ifndef BASESTUDENT_H
#define BASESTUDENT_H
enum MajorType {ENGLISH, HISTORY, MATH};
// *********************************************************************
// Base class. All other classes (Enlish, History, Math) inherit from
// this class.
// *********************************************************************
class BaseStudent
{
public:
BaseStudent();
BaseStudent(string fn, string ln, string m);
string GetFN(){return firstName;}
string GetLN(){return lastName;}
MajorType getMT(){return course;}
void SetFN(string fn){firstName = fn;}
void SetLN(string ln){lastName = ln;}
void SetMT(string m);
protected:
string firstName;
string lastName;
MajorType course;
}; // End Base class
// *********************************************************************
// Enlish class.
// *********************************************************************
class English: public BaseStudent
{
public:
English(string fn, string ln, string m, double a, double p, double mt, double f);
double FinalAverage();
double GetAttendance(){return attendance;}
double GetProject(){return project;}
double GetMidterm(){return midterm;}
double GetFinal(){return final;}
double GetFinalAverage(){return finalAverage;}
void SetAttendance(double a){attendance = a;}
void SetProject(double p){project = p;}
void SetMidterm(double m){midterm = m;}
void SetFinal(double f){final = f;}
void SetFinalAverage(double fa){finalAverage = fa;}
protected:
double attendance;
double project;
double midterm;
double final;
double finalAverage;
}; // End English class
// *********************************************************************
// History class.
// *********************************************************************
class History: public BaseStudent
{
public:
History(string fn, string ln, string m, double t, double mt, double f);
double FinalAverage();
double GetTermPaper(){return termPaper;}
double GetMidterm(){return midterm;}
double GetFinalExam(){return finalExam;}
double GetFinalAverage(){return finalAverage;}
double FinalExam(){return finalExam;}
void SetTermPaper(double t){termPaper = t;}
void SetMidterm(double m){midterm = m;}
void SetFinalExam(double f){finalExam = f;}
void SetFinalAverage(double fa){finalAverage = fa;}
protected:
double termPaper;
double midterm;
double finalExam;
double finalAverage;
}; // End History class.
// *********************************************************************
// Math class.
// *********************************************************************
class Math: public BaseStudent
{
public:
Math(string fn, string ln, string m, double q1, double q2, double q3,
double q4, double q, double t1, double t2, double f);
double FinalAverage();
double GetQuiz1(){return quiz1;}
double GetQuiz2(){return quiz2;}
double GetQuiz3(){return quiz3;}
double GetQuiz4(){return quiz4;}
double GetQuiz5(){return quiz5;}
double GetFinalExam(){return finalExam;}
double GetTest1(){return test1;}
double GetTest2(){return test2;}
double GetQuizAverage(){return quizAverage;}
double GetFinalAverage(){return finalAverage;}
void SetQuiz1(double q){quiz1 = q;}
void SetQuiz2(double q){quiz2 = q;}
void SetQuiz3(double q){quiz3 = q;}
void SetQuiz4(double q){quiz4 = q;}
void SetQuiz5(double q){quiz5 = q;}
void SetTest1(double q){test1 = q;}
void SetTest2(double q){test2 = q;}
void SetFinalExam(double q){finalExam = q;}
void SetQuizAverage();
void SetFinalAverage(double fa){finalAverage = fa;}
protected:
double quiz1;
double quiz2;
double quiz3;
double quiz4;
double quiz5;
double test1;
double test2;
double finalExam;
double quizAverage;
double finalAverage;
}; // End Math class.
#endif
Do I need some sort of implementation of virtual functions?
Here's my driver so far:
#include<iostream>
#include<fstream>
#include<string>
#include<iomanip>
#include"basestudent.h"
using namespace std;
int main(void)
{
string listSize;
string fileIn = "";
string fileOut = "";
string firstname ="";
string lastname ="";
string major = "";
string eolDummy;
int mQuiz1, mQuiz2, mQuiz3, mQuiz4, mQuiz5, mTest1, mTest2, mFinalExam;
int eAttendance, eProject, eMidterm, eFinalExam;
int hTermPaper, hMidterm, hFinalExam;
ifstream input;
ofstream output;
do{
input.clear();
cout << "Please enter the filename: ";
cin >> fileIn;
cout << "Please enter an output name: ";
cin >> fileOut;
input.open(fileIn);
if (!input)
cout << "Invalid file, please enter again." << endl;
} while(!input);
input >> listSize;
BaseStudent**studentlist = new BaseStudent*[atoi(listSize.c_str())];
int i = 0;
while (!input.eof())
{
getline(input, lastname, ',');
getline(input, firstname, '\n');
input >> major;
if (major == "Math") {
input >>mQuiz1>>mQuiz2>>mQuiz3>>mQuiz4>>mQuiz5>>mTest1>>mTest2
>>mFinalExam>>eolDummy;
// Math Constructor call
// Array += object
studentlist[i] = new Math(firstname,lastname,major,mQuiz1,mQuiz2,mQuiz3,mQuiz4,mQuiz5,
mTest1,mTest2,mFinalExam);
}
else if (major == "History"){
input >>hTermPaper>>hMidterm>>hFinalExam>>eolDummy;
// History Constructor call
// Array += object
studentlist[i] = new History(firstname,lastname,major,hTermPaper,hMidterm,hFinalExam);
}
else if(major == "English"){
input >>eAttendance>>eProject>>eMidterm>>eFinalExam>>eolDummy;
// English Constructor call
// Array += object
studentlist[i] = new English(firstname,lastname,major,eAttendance,eProject,eMidterm,eFinalExam);
}
i++;
}
output.open(fileOut);
output << "Student Grade Summary" << endl;
output << "---------------------" << endl << endl;
output << "ENGLISH CLASS "<<endl<<endl;
output << "Student Final Final Letter"<<endl;
output << "Name Exam Avg Grade"<<endl;
output << "----------------------------------------------------------------"<<endl;
for (int j=0; j<atoi(listSize.c_str()); j++){
if(studentlist[j]->getMT() == ENGLISH){
output << studentlist[j]->GetFN()<<" "<<studentlist[j]->GetLN();
output << right << setw(42) << studentlist[j]->
input.close();
output.close();
return 0;
}
When you take the pointer from your array, you need to cast it using dynamic_cast to the appropriate class
e.g.
BaseStudent *p = somearray[0];
if ( English* pEnglish = dynamic_cast<English*>(p) )
{
// call the methods
cout << p->FinalAverage();
...
}
else if ( History* pHistory = dynamic_cast<History*>(p) )
{
// call the methods
}
else if ( Math* pMath = dynamic_cast<Math*>(p) )
{
// call the methods
}
btw use a vector instead of a raw array, it is more convenient and safer.
std::vector<BaseStudent*> yourvector;