Errors: Redefinition of class and Previous Definition of class in C++ - c++

When I try to run the class with the class counter.cpp, I get the following error
In file included from Bounded_Counter.h:7:0,
from counterApp.cpp:4:
Lower_Bounded_Counter.h:9:7: error: redefinition of âclass LowerBoundedCounterâ
Lower_Bounded_Counter.h:9:7: error: previous definition of âclass LowerBoundedCounterâ
In file included from Bounded_Counter.h:8:0,
from counterApp.cpp:4:
Upper_Bounded_Counter.h:9:7: error: redefinition of âclass UpperBoundedCounterâ
Upper_Bounded_Counter.h:9:7: error: previous definition of âclass UpperBoundedCounterâ
I am aware that I am including some classes twice, but I don't know how to find it. Can you please help me find what I am doing wrong? There are 4 classes Counter.h, LowerBoundedCounter.h, UpperBoundedCounter.h, and BoundedCounter.h. LowerBoundedCounter.h and UpperBoundedCounter.h both include the Counter.h file. BoundedCounter.h includes both the LowerBoundedCounter.h and the UpperBoundedCounter.h files. The implementation file is counterApp.cpp (not provided here)
Here is the Counter.h class.
#ifndef COUNTER_H
#define COUNTER_H
#include <iostream>
class Counter{
private:
int val;
public:
Counter():val(0) {}
Counter(int val):val(val){}
void up(){
this->val++;
}
void down(){
this->val--;
}
int getVal() const {
return this->val;
}
friend std::ostream &operator <<(std::ostream &os, const Counter &counter) {
os << "A Counter with a value of " << counter.val;
return os;
}
};
#endif
Here is LowerBoundedCounter.h class. This class contains a 'Counter' object.
#ifndef LOWER_BOUNDED_COUNTER_H
#define LOWER_BOUNDER_COUNTER_H
#include<iostream>
#include "Counter.h"
class LowerBoundedCounter{
private:
Counter counter;
int limit;
public:
LowerBoundedCounter(int limit,int val):counter(val), limit(limit){
}
LowerBoundedCounter(int val):counter(val),limit(10){
}
LowerBoundedCounter():counter(),limit(0){
}
void up(){
if(getVal() > limit){
counter.up();
}
}
void down(){
counter.down();
}
int getLimit() const{
return this->limit;
}
int getVal() const{
return counter.getVal();
}
friend std::ostream &operator <<(std::ostream &os, const LowerBoundedCounter &LowerBoundedCounter){
os << "An LowerBoundedCounter with a value of " << LowerBoundedCounter.getVal() << " and a limit of "<<LowerBoundedCounter.limit;
return os;
}
};
#endif
Here's the UpperBoundedCounter.h class
#ifndef UPPER_BOUNDED_COUNTER_H
#define UPPER_BOUNDER_COUNTER_H
#include<iostream>
#include "Counter.h"
class UpperBoundedCounter{
private:
Counter counter;
int limit;
public:
UpperBoundedCounter(int limit,int val):counter(val), limit(limit){
}
UpperBoundedCounter(int val):counter(val),limit(10){
}
UpperBoundedCounter():counter(),limit(10){
}
void up(){
if(getVal() < limit){
counter.up();
}
}
void down(){
counter.down();
}
int getLimit() const {
return this->limit;
}
int getVal() const{
return counter.getVal();
}
friend std::ostream &operator <<(std::ostream &os, const UpperBoundedCounter &UpperBoundedCounter){
os << "An UpperBoundedCounter with a value of " << UpperBoundedCounter.getVal() << " and a limit of "<<UpperBoundedCounter.limit;
return os;
}
};
Finally, I have objects from all 3 of the above classes in BoundedCounter.h
#ifndef BOUNDED_COUNTER_H
#define BOUNDER_COUNTER_H
#include<iostream>
#include "Counter.h"
#include "Lower_Bounded_Counter.h"
#include "Upper_Bounded_Counter.h"
class BoundedCounter{
private:
Counter counter;
UpperBoundedCounter upperBoundedCounter;
LowerBoundedCounter lowerBoundedCounter;
public:
BoundedCounter(int val, int upperLimit, int lowerLimit):counter(val),upperBoundedCounter(upperLimit),lowerBoundedCounter(lowerLimit){
}
BoundedCounter(int val,int upperLimit):counter(val), upperBoundedCounter(upperLimit), lowerBoundedCounter(){
}
BoundedCounter(int val):counter(val),upperBoundedCounter(),lowerBoundedCounter(){
}
BoundedCounter():counter(), upperBoundedCounter(), lowerBoundedCounter(){
}
void up(){
if(getVal() < upperBoundedCounter.getLimit() && getVal() > lowerBoundedCounter.getLimit()){
counter.up();
}
}
void down(){
counter.down();
}
int getLowerLimit() const{
return lowerBoundedCounter.getLimit();
}
int getUpperLimit() const{
return upperBoundedCounter.getLimit();
}
int getVal() const{
return counter.getVal();
}
friend std::ostream &operator <<(std::ostream &os, const BoundedCounter &BoundedCounter){
os << "An BoundedCounter with a value of " << BoundedCounter.getVal() << " and a lower limit of "<<BoundedCounter.getLowerLimit()
<<" and a higher limit of "<<BoundedCounter.getUpperLimit();
return os;
}
};
#endif

Your header protection macro is wrong in all header files.
#ifndef BOUNDED_COUNTER_H
#define BOUNDER_COUNTER_H
Typo 'R'
There is a smaller problem in the UpperBoundedCounter.h, which does not have the closing #endif . But this will cause another problem.

Related

Difficulties with Pointers in C++ / Linking error

When compiling my code I get the following error:
LNK2019 unresolved external symbol "public: class QuantLib::Matrix
const & __cdecl SachLib::AWDCalculator::RSB(void)const "
(?RSB#AWDCalculator#SachLib##QEBAAEBVMatrix#QuantLib##XZ) referenced
in function "protected: void __cdecl
SachLib::CalculationEngine_Sach::set_results(class
boost::shared_ptr &)const "
(?set_results#CalculationEngine_Sach#SachLib##IEBAXAEAV?$shared_ptr#VAWDCalculator#SachLib###boost###Z)
It is found in CalculationEngine_Sach.obj in line 1.
Here is my code:
Abwicklungsdreieck and Gewichtungsfaktoren basically consists out of a Matrix and are obtained by its respective Reader. I think the names of their methods are unambiguous.
main.cpp:
#include "AbwicklungsdreieckReader.h"
#include "Abwicklungsdreieck.h"
#include "GewichtungsfaktorenReader.h"
#include "Gewichtungsfaktoren.h"
#include "Tarif_Sach.h"
#include "CalculationEngine_Sach.h"
#include "CalculationEngine_Sach_Typ1.h"
#if defined(QL_ENABLE_SESSIONS)
namespace QuantLib {
Integer sessionId() { return 0; }
}
#endif
using namespace QuantLib;
using namespace SachLib;
int main()
{
std::cout << "\n\n\nTest Chain-Ladder-Verfahren\n\n";
std::string input1 = "C:/Users/D91476/Desktop/LifeLib_Sol/awd.csv";
std::string input2 = "C:/Users/D91476/Desktop/LifeLib_Sol/gwf.csv";
boost::shared_ptr<PricingEngine> EngineTyp1(new CalculationEngine_Sach_Typ1());
SachLib::AbwicklungsdreieckReader input1Reader(input1);
SachLib::GewichtungsfaktorenReader input2Reader(input2);
SachLib::Abwicklungsdreieck AWD = input1Reader.get_awd();
std::cout << "\nInput 1: Abwicklungsdreieck\n\n";
std::cout << AWD.get_Matrix() << "\n";
SachLib::Gewichtungsfaktoren GWF = input2Reader.get_gwf();
std::cout << "\nInput 2: Gewichtungsfaktoren\n\n";
std::cout << GWF.get_Matrix();
Tarif_Sach *tarifsach1;
tarifsach1 = new Tarif_Sach_Typ1(AWD, GWF);
tarifsach1->setPricingEngine(EngineTyp1);
EngineTyp1->calculate();
}
By testing I found out that the error appears because of the following line:
boost::shared_ptr<PricingEngine> EngineTyp1(new CalculationEngine_Sach_Typ1());
AWDCalculator.h
#pragma once
#include "Tarif_Sach.h"
#include "Abwicklungsdreieck.h"
#include "Gewichtungsfaktoren.h"
#ifndef _AWDCalculator_H
#define _AWDCalculator_H
namespace SachLib {
class AWDCalculator {
public:
AWDCalculator();
AWDCalculator(Tarif_Sach::arguments *arguments);
AWDCalculator(Abwicklungsdreieck awd, Gewichtungsfaktoren gwf);
AWDCalculator(const AWDCalculator &obj);
AWDCalculator& operator=(AWDCalculator const& rhs);
//! Fills vectors.
void update(Tarif_Sach::arguments *arguments);
// Logic
void calculate(Abwicklungsdreieck awd, Gewichtungsfaktoren gwf);
//! \name Getter
//#{
const Abwicklungsdreieck& awd() const;
const Gewichtungsfaktoren& gwf() const;
const Matrix& estimated_costs_matrix() const;
const Matrix& RSB_all() const;
const Matrix& RSB() const;
//#}
Tarif_Sach::arguments *arguments_;
protected:
AWDCalculator *results_;
Abwicklungsdreieck awd_;
Gewichtungsfaktoren gwf_;
//! \name Outputs
//#{
Matrix estimated_costs_matrix_;
Matrix RSB_all_;
Matrix RSB_;
//#}
};
}
#endif
AWDCalculator.cpp
#include "AWDCalculator.h"
SachLib::AWDCalculator::AWDCalculator()
{
}
SachLib::AWDCalculator::AWDCalculator(Tarif_Sach::arguments *arguments)
: AWDCalculator(arguments->awd, arguments->gwf)
{
arguments_ = arguments;
}
SachLib::AWDCalculator::AWDCalculator(Abwicklungsdreieck awd, Gewichtungsfaktoren gwf)
: awd_(awd),
gwf_(gwf)
{
results_ = new AWDCalculator(awd, gwf);
calculate(awd, gwf);
}
SachLib::AWDCalculator::AWDCalculator(const AWDCalculator& obj)
{
arguments_ = obj.arguments_;
awd_ = obj.awd_;
gwf_ = obj.gwf_;
}
SachLib::AWDCalculator& SachLib::AWDCalculator::operator=(AWDCalculator const& rhs)
{
arguments_ = rhs.arguments_;
awd_ = rhs.awd_;
gwf_ = rhs.gwf_;
return *this;
}
void SachLib::AWDCalculator::update(Tarif_Sach::arguments *arguments)
{
results_ = new AWDCalculator(arguments);
arguments_ = arguments;
awd_ = arguments->awd;
gwf_ = arguments->gwf;
}
void SachLib::AWDCalculator::calculate(Abwicklungsdreieck awd, Gewichtungsfaktoren gwf)
{
// RSB_, RSB_all_ and estimated_costs_matrix_ get calculated here with the input awd and gwf
}
inline const Matrix& SachLib::AWDCalculator::estimated_costs_matrix() const
{
return estimated_costs_matrix_;
}
inline const Matrix& SachLib::AWDCalculator::RSB_all() const
{
return RSB_all_;
}
inline const Matrix& SachLib::AWDCalculator::RSB() const
{
return RSB_;
}
inline const SachLib::Abwicklungsdreieck& SachLib::AWDCalculator::awd() const
{
return awd_;
}
inline const SachLib::Gewichtungsfaktoren& SachLib::AWDCalculator::gwf() const
{
return gwf_;
}
CalculationEngine_Sach.h
#pragma once
#ifndef SachLib_calculationengine_sach_hpp
#define SachLib_calculationengine_sach_hpp
#include "Tarif_Sach.h"
#include "AWDCalculator.h"
using namespace QuantLib;
namespace SachLib {
class CalculationEngine_Sach : public Tarif_Sach::engine {
public:
CalculationEngine_Sach();
void calculate() const;
protected:
mutable boost::shared_ptr<AWDCalculator> AWDCalculator_;
void set_results(boost::shared_ptr<AWDCalculator> &awdCalculator) const;
};
}
#endif
CalculationEngine_Sach.cpp
#include "CalculationEngine_Sach.h"
#include "Tarif_Sach.h"
#include "AWDCalculator.h"
using namespace QuantLib;
namespace SachLib {
CalculationEngine_Sach::CalculationEngine_Sach()
{
}
void CalculationEngine_Sach::calculate() const
{
arguments_.AWDCalculator->update(&arguments_);
CalculationEngine_Sach::set_results(arguments_.AWDCalculator);
}
void CalculationEngine_Sach::set_results(boost::shared_ptr<AWDCalculator> &awdCalculator) const
{
results_.estimated_costs_matrix = awdCalculator->estimated_costs_matrix();
results_.RSB_all = awdCalculator->RSB_all();
results_.RSB = awdCalculator->RSB();
// because of the above three lines the error appears
}
}
CalculationEngine_Sach_Typ1.h
#pragma once
#include "CalculationEngine_Sach.h"
namespace SachLib {
class CalculationEngine_Sach_Typ1 : public CalculationEngine_Sach
{
public:
CalculationEngine_Sach_Typ1();
};
}
CalculationEngine_Sach_Typ1.cpp
#include "CalculationEngine_Sach_Typ1.h"
SachLib::CalculationEngine_Sach_Typ1::CalculationEngine_Sach_Typ1()
{}
If anyone could help I'd be much grateful.
You marked that function inline in the .cpp:
inline const Matrix& SachLib::AWDCalculator::RSB() const
In this case the compiler does not have to generate an out-of-line definition, unless it is needed in that translation unit (e.g. function address is taken). And that causes the linker error.
Remove inline from the function definition to make the compiler generate an out-of-line definition to fix the linker error.
you'll need to find the include file that has the definition for "Matrix" - that's what the error is showing.

How can I fix g++ Undefined symbols for architecture x86_64 error? I use IDE clion

I have only one custom class with .h and .cpp files but I get error while trying to create an instance of this class from main.cpp (using IDE clion).
I am just a beginner and reading C++ primer learning class, if there are some inappropriate things please point out.
main.cpp
#include "Fun.h"
void Solve();
int main()
{
Solve();
return 0;
}
void Solve()
{
Sales_data total;
if(read(cin,total)){ //read the first record
Sales_data temp;
while(read(cin,temp)){
if(temp.isbn() == total.isbn())
total.combine(temp);
else{
print(cout,total) << endl;
total = temp;
}
}
print(cout,total);
}//if
else{
cerr << "No data!?" << endl;
}
}
Fun.cpp
#include "Fun.h"
using std::istream;
using std::ostream;
double Sales_data ::avg_price() const {
if(units_sold)
return revenue/units_sold;
else
return 0;
}
Sales_data& Sales_data:: combine(const Sales_data& rhs){
units_sold += rhs.units_sold;
revenue += rhs.revenue;
return *this;
}
istream &read(istream &is,Sales_data &item)
{
double price = 0;
is >> item.bookNo >> item.units_sold >> price;
item.revenue = price * item.units_sold;
return is;
}
ostream &print(ostream &os, const Sales_data &item)
{
os << item.isbn() << " " << item.units_sold << " "
<< item.revenue << " " << item.avg_price() ;
return os;
}
Sales_data add(const Sales_data& lhs,const Sales_data& rhs)
{
Sales_data sum = lhs;
sum.combine(rhs);
return sum;
}
Fun.h
#ifndef PROJECT1_FUN_H
#define PROJECT1_FUN_H
#include <cstdio>
#include <cstring>
#include <cassert>
#include <vector>
#include <iostream>
using std::istream;
using std::ostream;
using std :: cin;
using std :: cout;
using std :: cerr;
using std :: endl;
struct Sales_data{
std::string isbn()const{return bookNo;}
Sales_data& combine(const Sales_data&);
double avg_price() const;
std::string bookNo;
unsigned units_sold = 0;
double revenue = 0;
};
Sales_data add(const Sales_data&,const Sales_data&);
istream &read(istream &,Sales_data &);
ostream &print(ostream &,Sales_data &);
#endif //PROJECT1_FUN_H
This is the error information:
I wonder what caused the problem?
I think the problem is that declaration and definition of the print function are different (the Sales_data parameter is a reference in declaration while is a constant reference in definition):
ostream &print(ostream &,Sales_data &); // Fun.h
ostream &print(ostream &os, const Sales_data &item) // Fun.cpp
Change the declaration in the header file to:
ostream &print(ostream &, const Sales_data &);

error C2509: member function not declared in derived class [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I have base class State and derived class InitialState.When i build solution compiler show error C2509: 'setView': member function not declared in 'InitialState' and I don't know why...
Here is State.h :
#ifndef STATE_H
#define STATE_H
#include<iostream>
using namespace std;
class State {
public:
State() { isPrototype = true; }
virtual void execute() = 0;
virtual void setView(ostream& screen) const = 0;
virtual void onEnter() { system("CLS"); setView(cout); }
virtual void onExit() = 0;
private:
bool isPrototype;
State* nextState;
};
#endif
InitialState.h :
#ifndef INITIAL_STATE_H
#define INITIAL_STATE_H
#include"State.h"
class InitialState : public State {
public:
void execute() {}
void onExit() {}
void setView(ostream& screen) const;
};
#endif
and InitialState.cpp:
#include"InitialState.h"
void InitialState::setView(ostream& screen) const {
screen << "Welcome!" << endl;
screen << "Please select what you want to do: " << endl << "1.Load card" << endl << "0.Exit" << endl;
}
I have tried to add key word "virtual" in the front of functions in InitialState.h , but it doesn't change anything...also when I delete InitialState.cpp the code compiles normaly.
Here is the AtmTest.cpp:
#include "PaymentCard.h"
//#include "Atm.h"
int main() {
return 0;
}
but it has nothing with State...
and here are the other classes:
Atm.h:
#ifndef ATM_H
#define ATM_H
#include<iostream>
using namespace std;
class Atm {
public:
static Atm* get();
static void release() { delete instance; instance = nullptr; } //Singleton
private:
int serialNumber;
string bankName;
string location;
//Singleton:
Atm();
static Atm* instance;
Atm(const Atm& m) = delete;
Atm& operator=(const Atm& m) = delete;
Atm(Atm&&) = delete;
Atm& operator=(Atm&& m) = delete;
};
#endif
Atm.cpp:
#include"Atm.h"
//Singleton:
Atm* Atm::instance = nullptr;
Atm* Atm::get() {
if (instance == nullptr) {
instance = new Atm();
}
return instance;
}
PaymentCard.h:
#ifndef PAYMENT_CARD_H
#define PAYMENT_CARD_H
#include<iostream>
using namespace std;
class PaymentCard {
public:
PaymentCard(string clientName);
void addMoney(unsigned int amount) { currentAmount += amount; }
void withdrawMoney(int amount);
friend ostream& operator<< (ostream&, const PaymentCard&);
private:
static int NumberGenerator;
unsigned int serialNumber;
string clientName;
int currentAmount;
};
#endif
PaymentCard.cpp:
#include"PaymentCard.h"
int PaymentCard::NumberGenerator = 0;
PaymentCard::PaymentCard(string clientName) {
currentAmount = 0;
this->clientName = clientName;
serialNumber = NumberGenerator++;
}
void PaymentCard::withdrawMoney(int amount) {
if (amount > currentAmount)cout << "Ovde ide izuzetak";
else currentAmount -= amount;
}
ostream& operator<< (ostream &os, const PaymentCard& card){
os << card.serialNumber + 1 << ". Client: " << card.clientName << endl;
return os;
}
This code is not near the finish, but it worked until i have made SetView in InitialState, so idk what happened..
The problem: InitialState.h is precompiled, and you are linking to a prior version of InitialState.h. Clean, rebuild, and/or disable precompiled headers altogether.
I suspect that, because:
I can reproduce the error by commenting out the declaration of setView() in InitialState.h
The resulting error message refers to line 3 of InitialState.cpp and the error message you posted refers to line 6, which indicates that the posted source code did not produce that error message.
To reproduce the error, one has to comment out the setView() decalration from the InitialState class:
class InitialState : public State {
public:
void execute() {}
void onExit() {}
//void setView(ostream& screen) const;
};
Then one gets the following error message:
1>InitialState.cpp(3): error C2509: 'setView' : member function not declared in 'InitialState'
1> c:\users\laci\desktop\samples\stackoverflow\InitialState.h(6) : see declaration of 'InitialState'

Unable to find segmentation fault error in c++

I have 3 c++ files, instrument.h, percussion.h, and instrumentApp.cpp. Instrument.h is the base class and percussion.h inherits it. Percussion objects are defined and implemented in the instrumentApp.cpp class. Whenever I run instrumentApp.cpp, I get the segmentation fault error.
I have managed to trace the cause of the error to the overloaded << operator function in percussion.h where I am calling a method of the base class instrument.h. For some reason, my code is unable to call methods of the base class and I don't know why. Can you please help me?
Here is the instrument.h class
#ifndef INSTRUMENT_H
#define INSTRUMENT_H
class Instrument{
private:
std::string name;
std::string sound;
std::string lowRange;
std::string highRange;
public:
Instrument(std::string name, std::string sound, std::string lowRange, std::string highRange){
this->name = name;
this->sound = sound;
this->lowRange = lowRange;
this->highRange = highRange;
}
std::string getName() const{
return this->name;
}
std::string play()const {
return this->sound;
}
std::string getLowRange() const{
return this->lowRange;
}
std::string getHighRange() const{
return this->highRange;
}
bool isWind();
bool isWoodWind();
bool isBrass();
bool isKeyboard();
bool isPercussion();
bool isStrings();
friend std::ostream &operator <<(std::ostream &os, const Instrument &instrument){
}
};
#endif
Here is the percussion.h class
#ifndef PERCUSSION_H
#define PERCUSSION_H
#include "instrument.h"
class Percussion : public Instrument{
private:
bool struck;
public:
Percussion(std::string name, std::string sound, std::string lowRange, std::string highRange, bool struck) : Instrument(name,sound,lowRange,highRange){
this->struck=struck;
}
bool isStrucked() const {
return this->struck;
}
bool isPercussion() {
return true;
}
std::string getType() const{
if(this->struck){
return "struck";
}
else{
return "";
}
}
friend std::ostream &operator <<(std::ostream &os, Percussion &percussion){
//The error stems from this line of code
//Apparently, the getName() method in the base class isn't called
os<<percussion.getName();
}
};
#endif
Here is the implementation file instrumentApp.cpp
#include <iostream>
#include <string>
#include <sstream>
#include <cstdlib>
#include "instrument.h"
#include "percussion.h"
#include "strings.h"
using namespace std;
int main() {
Percussion timpani("timpani", "boom", "D2", "A2", true);
cout << timpani << endl;
Percussion harp("harp", "pling", "Cb1", "F#7", false);
cout << harp << endl;
return 0;
}
The problem here is that I wasn't returning the os object when I overloaded the << operator.
The fix is as follows in the percussion.h file
friend std::ostream &operator <<(std::ostream &os, Percussion &percussion){
os<<percussion.getName();
return os;
}

Overloading << operator to print vector contents

I've looked up information for overloading the << operator, and it seems like I did everything correctly, but I keep getting a compile error. I've friended this function in my header file, and placed a prototype at the top of my cpp file.
My University.h:
#ifndef UNIVERSITY_H
#define UNIVERSITY_H
#include <string>
#include <vector>
#include <iostream>
using namespace std;
#include "Department.h"
#include "Student.h"
#include "Course.h"
#include "Faculty.h"
#include "Person.h"
class University
{
friend ostream& operator<< (ostream& os, const vector<Department>& D);
friend ostream& operator<< (ostream& os, const Department& department);
protected:
vector<Department> Departments;
vector<Student> Students;
vector<Course> Courses;
vector<Faculty> Faculties;
static bool failure;
static bool success;
public:
bool CreateNewDepartment(string dName, string dLocation, long dChairID);
bool ValidFaculty(long dChairID);
};
#endif
My University.cpp:
#ifndef UNIVERSITY_CPP
#define UNIVERSITY_CPP
#include<string>
#include<vector>
#include<iostream>
using namespace std;
#include "University.h"
ostream& operator<<(ostream& os, const vector<Department>& D);
ostream& operator<<(ostream& os, const Department& department);
bool University::failure = false;
bool University::success = true;
bool University::CreateNewDepartment(string dName, string dLocation, long dChairID)
{
if((dChairID != 0) && (ValidFaculty(dChairID)== University::failure))
{
Department D(dName, dLocation, dChairID);
Departments.push_back(D);
for (int i = 0; i < Departments.size(); i++)
cout << Departments;
return University::success;
}
return University::failure;
}
bool University::ValidFaculty(long dChairID)
{
for (int i = 0; i < Faculties.size(); i++)
{
if (Faculties[i].ID == dChairID)
return University::success;
}
return University::failure;
}
ostream& operator<<(ostream& os, const vector<Department>& D)
{
for (int i = 0; i < D.size(); i++)
os << D[i] << endl;
os << "\n";
return os;
}
ostream& operator<< (ostream& os, const Department& department)
{
department.Print(os);
return os;
}
#endif
My Department.h:
#ifndef DEPARTMENT_H
#define DEPARTMENT_H
#include<vector>
#include<string>
#include<iostream>
using namespace std;
class Department
{
friend class University;
friend ostream& operator<< (ostream& os, Department& department);
protected:
long ID;
string name;
string location;
long chairID;
static long nextDepartID;
public:
Department();
Department(string dName, string dLocation, long dChairID);
void Get();
void Print(ostream& os)const;
};
#endif
My Department.cpp:
#ifndef DEPARTMENT_CPP
#define DEPARTMENT_CPP
#include<iostream>
#include<string>
using namespace std;
#include "Department.h"
long Department::nextDepartID = 100;
Department::Department()
{
ID = nextDepartID++;
name = "Null";
location = "Null";
chairID = 0;
}
Department::Department(string dName, string dLocation, long dChairID):name(dName), location(dLocation), chairID(dChairID)
{
ID = nextDepartID++;
}
void Department::Get()
{
}
void Department::Print(ostream& os)const
{
os << "\n";
os << ID << endl;
os << name << endl;
os << location << endl;
os << chairID << endl;
os <<"\n\n";
}
ostream& operator<< (ostream& os, const Department& department)
{
department.Print(os);
return os;
}
#endif
Now everything can be seen that pertains only to this problem. The only error I receive now is that void value is not being ignored.
Snippet of error:
University.cpp: In function ‘std::ostream& operator<<(std::ostream&, const Department&)’:
University.cpp:53: error: void value not ignored as it ought to be
Department.cpp: In function ‘std::ostream& operator<<(std::ostream&, const Department&)’:
Department.cpp:42: error: void value not ignored as it ought to be
FINAL EDIT:
Thanks to everyone that helped me. I definitely have a better understanding of operator overloading now...especially when it deals with printing vectors of user-defined types!
The complaint was that while your function to iterate over and print the vector contents may have been correct, the actual object contained by the vector did not have an operator<< specified.
You need to have one.
If you already have a method called Print() in your Department class, you could simply create an overload for operator<< as follows:
std::ostream& operator<<(std::ostream& os, const Department& department) {
os<<department.Print();
return os;
}
I had prepared the following code before you posted your update. Maybe it can help you.
#include<iostream>
#include<vector>
#include<string>
class Department {
public:
Department(const std::string& name)
: m_name(name) { }
std::string name() const {
return m_name;
}
private:
std::string m_name;
};
// If you were to comment this function, you would receive the
// complaint that there is no operator<< defined.
std::ostream& operator<<(std::ostream& os, const Department& department) {
os<<"Department(\""<<department.name()<<"\")";
return os;
}
// This is a simple implementation of a method that will print the
// contents of a vector of arbitrary type (not only vectors, actually:
// any container that supports the range-based iteration): it requires
// C++11.
template<typename T>
void show(const T& container) {
for(const auto& item : container) {
std::cout<<item<<std::endl;
}
}
int main() {
std::vector<Department> deps = {{"Health"}, {"Defense"}, {"Education"}};
show(deps);
}
Compile with g++ example.cpp -std=c++11 -Wall -Wextra (I used OS X 10.7.4 and GCC 4.8.1) to get:
$ ./a.out
Department("Health")
Department("Defense")
Department("Education")