I have a class within a namespace like following.
test.h
#include <iostream>
using std::cout;
namespace n1
{
class myClass;
}
class n1::myClass
{
public:
myClass(int na, int nb):a(na), b(nb){}
private:
int a;
int b;
friend std::ostream& operator << (std::ostream & stream, const n1::myClass& cls);
};
test.cpp
#include "test.h"
std::ostream& operator << (std::ostream & str, const n1::myClass& cls)
{
str << cls.a << " " << cls.b << std::endl;
}
On Compilation, I am getting following error.
test.h: In function ‘std::ostream& operator<<(std::ostream&, const n1::myClass&)’:
test.h:13:6: error: ‘int n1::myClass::a’ is private
test.cpp:5:13: error: within this context
test.h:14:6: error: ‘int n1::myClass::b’ is private
test.cpp:5:29: error: within this context
How do I get past the errors?
You can define the operator << inside the namespace which myClass is defined:
namespace n1
{
std::ostream& operator << (std::ostream & str, const myClass& cls)
{
str << cls.a << " " << cls.b << std::endl;
}
}
Because you've promised myClass has a friend in name-space n1 but you actually declare the operator in global name-space.
Related
Just got into C++ and I have a quick question.
After compiling with
g++ *.cpp -o output
I receive this error:
error: 'ostream' in 'class Dollar' does not name a type
These are my three files:
main.cpp
#include <iostream>
#include "Currency.h"
#include "Dollar.h"
using namespace std;
int main(void) {
Currency *cp = new Dollar;
// I want this to print "printed in Dollar in overloaded << operator"
cout << cp;
return 0;
}
Dollar.cpp
#include <iostream>
#include "Dollar.h"
using namespace std;
void Dollar::show() {
cout << "printed in Dollar";
}
ostream & operator << (ostream &out, const Dollar &d) {
out << "printed in Dollar in overloaded << operator";
}
Dollar.h
#include "Currency.h"
#ifndef DOLLAR_H
#define DOLLAR_H
class Dollar: public Currency {
public:
void show();
};
ostream & operator << (ostream &out, const Dollar &d);
#endif
Thank you for your time, and everything helps!
You have a number of errors in the code.
You heavily use using namespace std. This is a bad practice. In particular, this led to the error you faced: you don't have using namespace std in Dollar.h, thus the compiler has no idea what ostream means. Either put using namespace std in Dollar.h too, or better just stop using it and specify the std namespace directly, as in std::ostream.
You use std::ostream in your headers, but you don't include the corresponding standard library header <ostream> in them (<ostream> contains the definition of std::ostream class; for the full I/O library include <iostream>). A really good practice is to include all the dependencies of the header in the header itself, so that it is self-contained and can be safely included anywhere.
You are implementing a stream output operator with signature std::ostream & operator << (std::ostream &, Dollar const &), which is perfectly valid. However, you call it for a pointer to type Dollar. You should rather call it with the object itself, not the pointer, so you should dereference the pointer: std::cout << *cp;.
You implemented the output operator for the Dollar class, but use it for a variable of type Currency: this won't work. There is a way to do this - there do exist virtual methods for this exact reason. However, in this case the operator is a free function, thus it cannot be virtual. So, you should probably add a virtual print method to your Currency class, implement it in Dollar, and call it from output operator:
#include <iostream>
class Currency {
public:
virtual void print (std::ostream &) const = 0;
};
class Dollar : public Currency {
void print (std::ostream & out) const override {
out << "A dollar";
}
};
std::ostream & operator << (std::ostream & out, Currency const & c) {
c.print(out);
return out;
}
int main(/* void is redundant here */) {
Currency *cp = new Dollar;
std::cout << *cp;
// return 0 is redundant in main
}
You need to #include <iostream> within Dollar.h so that your std::ostream & operator is resolved by the compiler.
Update: I made Sergii's changes below, but now I get the error: undefined reference to `cs202::operator<<(std::basic_ostream >&, cs202::Rational const&)'. Any ideas how to fix this? Thanks
I would appreciate help figuring out why I am getting this error:
"error: 'output' is not a member of namespace 'cs202'"
I have a class called Rational as follows:
#ifndef RATIONAL_H
#define RATIONAL_H
namespace cs202{
class Rational
{
private:
int m_numerator;
int m_denominator;
public:
Rational(int nNumerator = 0, int nDenominator = 1) {
m_numerator = nNumerator;
m_denominator = nDenominator;
}
int getNumerator(){return m_numerator;}
int getDenominator(){return m_denominator;}
friend std::ostream& operator<<(std::ostream& output, const Rational& cRational);
};
}
#endif
The implementation file for the friend function which overrides the << operator looks like this:
#include "rational.h"
namespace cs202{
friend std::ostream& operator<<(std::ostream& output, const Rational& cRational)
{
output << cRational.m_numerator << "/" << cRational.m_denominator;
return output;
}
}
Finally, Main looks like this:
#include <iostream>
#include "rational.h"
using namespace std;
using namespace cs202;
int main()
{
Rational fraction1(1, 4);
cs202::output << fraction1 << endl;
return 0;
}
I have tried using cout instead of cs202:output, I have tried with and without the namespace cs202 (which is a requirement of the assignment), and I have tried making the operator overload function a member function of the class rather than a friend function to no avail.
What am I missing? Thanks
I suppose you want it out to standard output (to console)
int main()
{
Rational fraction1(1, 4);
std::cout << fraction1 << endl;
return 0;
}
Also you do not need friend here. "Friend" keyword is used only in a class
#include "rational.h"
namespace cs202{
std::ostream& operator<<(std::ostream& output, const Rational& cRational)
{
output << cRational.m_numerator << "/" << cRational.m_denominator;
return output;
}
}
Thanks, I figured it out. I had to change the placement of the {} for the namespace.
I get this when i try to compile:
../Monster.h:26:9: error: ‘int ProjectIV::Monster::con’ is private
`int con;`
^
../Monster.cpp:17:39: error: within this context
cout << "Constitution: " << monster.con << endl;
^
make: * [Monster.o] Error 1
From what I understand making operator<< a friend should allow it to access int con. What am I not seeing.
Monster.h:
#ifndef MONSTER_H_
#define MONSTER_H_
#include <iostream>
using std::cout;
using std::endl;
using std::ostream;
#include <string>
using std::string;
namespace ProjectIV
{
class Monster
{
friend ostream &operator<< (ostream &out, const Monster &monster);
public:
Monster(int con);
private:
int con;
};
} /* namespace ProjectIV */
#endif /* MONSTER_H_ */
Monster.cpp:
#include "Monster.h"
ostream &operator<< (ostream &out, const ProjectIV::Monster &monster)
{
cout << "Constitution: " << monster.con << endl;
return out;
}
ProjectIV::Monster::Monster(int con): con(con)
{}
main.cpp:
#include "Monster.h"
using namespace ProjectIV;
int main()
{
Monster Gojira(140);
cout << Gojira << endl;
return 0;
}
This:
ostream& operator<<(ostream& out, const ProjectIV::Monster& monster)
should be:
ostream& ProjectIV::operator<<(ostream& out, const ProjectIV::Monster& monster)
Here your not working example, and here is the working one.
Also, as per AndreyT's comment, you should add a function declaration before the friend declaration:
namespace ProjectIV {
class Monster {
friend ostream& operator<<(ostream& out, const Monster& monster);
public:
Monster(int con);
private:
int con;
};
ostream& operator<<(ostream& out, const Monster& monster);
// ^^^ this
}
There are two problems with your code.
Firstly, the friend declaration inside Monster class refers to ProjectIV::operator << function. It is ProjectIV::operator << that will become the friend of Monster. What you defined in your Monster.cpp file is actually a ::operator <<. This is a completely different function that is not a friend of Monster. This is why you get the error.
So, you need to decide what function you want to make a friend - the one in global namespace or the one in ProjectIV namespace - and act accordingly.
If you want to make your operator << a member of ProjectIV namespace, you run into the second problem. Friend declarations refer to member of enclosing namespace, but they don't introduce the corresponding declarations into the enclosing namespace. It is still your responsibility to add a declaration for operator << in ProjectIV
namespace ProjectIV
{
class Monster
{
friend ostream &operator<< (ostream &out, const Monster &monster);
public:
Monster(int con);
private:
int con;
};
ostream &operator<< (ostream &out, const Monster &monster);
} /* namespace ProjectIV */
and then later define it as a member of ProjectIV
ostream &ProjectIV::operator<< (ostream &out, const ProjectIV::Monster &monster)
{
cout << "Constitution: " << monster.con << endl;
return out;
}
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")
xml_attribute.h
#pragma once
#ifndef XML_ATTRIBUTET_H
#define XML_ATTRIBUTET_H
#include <string>
#include <iostream>
struct XML_AttributeT{
std::string tag;
std::string value;
//constructors
explicit XML_AttributeT(std::string const& tag, std::string const& value);
explicit XML_AttributeT(void);
//overloaded extraction operator
friend std::ostream& operator << (std::ostream &out, XML_AttributeT const& attribute);
};
#endif
xml_attribute.cpp
#include "xml_attribute.h"
//Constructors
XML_AttributeT::XML_AttributeT(std::string const& tag_, std::string const& value_)
: tag{tag_}
, value{value_}
{}
XML_AttributeT::XML_AttributeT(void){}
//overloaded extraction operator
std::ostream& operator << (std::ostream &out, XML_AttributeT const attribute){
return out << attribute.tag << "=" << attribute.value;
}
driver.cpp
#include <iostream>
#include <cstdlib>
#include "xml_attribute.h"
int main(){
using namespace std;
XML_AttributeT a();
cout << a << endl;
return EXIT_SUCCESS;
}
The output from the driver is a '1' but I want it to be an '=' sign.
Why is it outputting the reference to a?
If I change XML_AttributeT a(); to XML_AttributeT a; it doesn't even compile.
What did I do wrong?
chris is correct. Your initial issue is that XML_AttributeT a() is interpreted as a function declaration. clang++ will actually warn you of this:
Untitled.cpp:33:21: warning: empty parentheses interpreted as a function declaration [-Wvexing-parse]
XML_AttributeT a();
You can use a{} instead to fix this.
At this point you get a new error:
Untitled.cpp:34:10: error: use of overloaded operator '<<' is ambiguous (with operand types 'ostream' (aka 'basic_ostream<char>') and 'XML_AttributeT')
cout << a << endl;
This is because of what jogojapan said. Your implemented operator<< is using XML_AttributeT const as the attribute type instead of XML_AttributeT const &. If you fix that, then it compiles and gives you the result you want.