#include <iostream>
#include <fstream>
class obj
{
public:
int i;
friend ostream& operator<<(ostream& stream, obj o);
}
void main()
{
obj o;
ofstream fout("data.txt");
fout<<o;
fout.close();
}
This is the my code, am getting error.
error : ostream : ambiguous symbol.
any one can help me.
You need to specify the namespace. Prefix ostream with std - i.e. std::ostream
Also, you should pass the obj type by const reference to the operator:
friend ostream& operator<<(ostream& stream, const obj& o);
You didn't use namespace std (using namespace std is habit anyway) so the compiler doesn't know what on earth an ostream is.In addition to that, you didn't actually define operator<<, only declared it, so even if it recognizes it, it won't know what to do since you didn't tell it.
As I see it you need to
Add
using std::ostream;
using std::ofstream;
Add a ; after the class declaration
Povide an implementation for the << operator.
In the end you should end up with something like:
#include <iostream>
#include <fstream>
using std::ostream;
using std::ofstream;
class obj
{
public:
int i;
friend ostream& operator<<(ostream& stream, const obj& o);
};
ostream& operator<<(ostream& stream, const obj& o)
{
std::cout << o.i;
return stream;
}
int main()
{
obj o;
ofstream fout("data.txt");
fout << o;
fout.close();
}
ofstream is in namespace std, so you need to declare fout like this:
std::ofstream fout("data.txt");
I'll assume you simply omitted the definition of your operator<< function for simplicity. Obviously, you'll need to write the body of that function for your next line to compile.
ostream is a member of the std:: namespace, so either put a using namespace std; before your class declaration or explicitly refer to it with std::ostream.
Consider passing your object in as a reference otherwise a new obj object will be created each time via the copy constructor.
friend ostream& operator<<(ostream& stream, obj& o);
Related
I've declared an operator<< overload for time_point in the global namespace and also one for a::Foo in the a namespace. When I try to print a time_point in a function also defined in namespace a, I get the error:
Invalid operands to binary expression.
Why is this, and what is the best solution?
#include <iostream>
#include <chrono>
std::ostream &operator<<(std::ostream &os,
const std::chrono::system_clock::time_point &time_point);
namespace a {
class Foo;
std::ostream &operator<<(std::ostream &os, const a::Foo &foo);
void print_time() {
std::cout << std::chrono::system_clock::now(); // error here!
}
}
int main() {
a::print_time();
}
The reason is simple: a::operator<< shadows your ::operator<< since they have the same name. This is why operators basically have to share a namespace with their classes: such shadowing is to be expected, and so ADL (as discussed in the comments) is the only reliable means of finding them.
How to let a wrapper class in a namespace know that in the outer/global namespace there may exist overloaded operators for the object that it wraps?
Note: I've heard of ADL, or Koenig lookup, but I met a real problem.
The Real Design Problem
I want to design a header-only library. Say I put everything in namespace my. The part related to this question can be simplified to something like a template wrapper item.
// my.hpp
#include <iostream>
namespace my
{
template<typename T>
struct item
{
T thing;
item(T t) : thing(t) {}
};
template<typename T>
std::ostream & operator<<(std::ostream & os, const item<T> & it)
{
os << it.thing;
return os;
}
}
With item what I want to achieve is that:
item<T> wraps a T object (with T object to be provided by user)
If operator<<(std::ostream &, const T &) is not defined in <iostream>, then I assume the user has overloaded operator<<(std::ostream &, const T &), and I want operator<<(std::ostream &, const item<T> &) to call it.
A Concrete User Example
Consider a set of user code that does so for T = std::vector<double>
// user.hpp
// #include guard omitted
#include <iostream>
#include <vector>
std::ostream & operator<<(std::ostream &, const std::vector<double> &);
and
// user.cpp
#include <iostream>
#include <vector>
std::ostream & operator<<(std::ostream & os, const std::vector<double> & v)
{
for (const auto & e : v)
os << e << " | ";
return os;
}
int main()
{
std::vector<double> vec = {3.14, 2.83};
std::cout << my::item<std::vector<double>>(vec);
}
Now if the user put
#include "user.hpp"
#include "my.hpp"
at the beginning of user.cpp, everything would be fine and g++ user.cpp would compile as expected.
However, if the user changed the order and put
#include "my.hpp"
#include "user.hpp"
the compiler would generate an error saying
my.hpp: In function 'std::ostream& my::operator<<(std::ostream&, const my::item<T>&)':
my.hpp:15:23: error: '::operator<<' has not been declared
Certainly I do not want the result to be dependent on the order of #include.
My question is: As a designer of namespace my and wrapper item<T>, what can I do to my and item<T> so that item<T> can correctly spot and call operator<<(std::ostream, const T &) if it is provided by user?
Thank you for your time!
Update: For your information, g++ --version returns
g++ (x86_64-posix-seh-rev0, Built by MinGW-W64 project) 7.3.0
After reading a question and answer on meta, and following suggestions from comments, I am moving some "updates" in my own question and posting them formally as a self-answer. I am doing so in the hope that this will help someone in future who happen to meet the same kind of problem. Thank you!
As #xskxzr correctly points out in the comment, there is something bad in the user code. To be specific,
it is bad to declare functions/operations whose parameters are all std entities as you cannot add such declarations into std to make use of ADL
In this case, the problem lies on the side of the user, not on the designer.
Now if the user made a change
// user.hpp
#include <iostream>
#include <vector>
// CHANGE: (privately) inherit from std::vector<double>, rather than overload directly
struct DoubleVector : private std::vector<double>
{
using std::vector<double>::vector;
friend
std::ostream & operator<<(std::ostream &, const DoubleVector &);
};
std::ostream & operator<<(std::ostream &, const DoubleVector &);
and
// user.cpp
#include "my.hpp"
#include "user.hpp"
#include <iostream>
#include <vector>
// CHANGE: use a user-defined DoubleVector class
std::ostream & operator<<(std::ostream & os, const DoubleVector & c)
{
for (const auto & e : c)
os << e << " | ";
return os;
}
int main()
{
DoubleVector vec = {3.14, 2.83};
std::cout << my::item<DoubleVector>(vec);
}
Then the user code would compile regardless of the order of #include "my.hpp" and #include "user.hpp".
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.
I'm writing a header only matrix3x3 implementation which I want to be independent and not relying on other headers except for a vector3 header which i also wrote.
Currently, I want it to overload ostream << operator but I don't want to include the iostream in it.
Is it possible to make the overloading optional and work if ostream is included, and if its not included to have all the rest work fine just without the overload?
I thought about the possibility of checking if the ostream header is included but it has a major flaw because it would not work correctly if iostream was included after the matrix3x3 header.
Edit:
I've replaced iostream with ostream as i think it created a bit of confusion regarding the point of the question.
Why not use <iosfwd>?
Example:
#include <iosfwd>
class Example
{
public:
Example(int i) : i(i) {}
private:
int i;
friend std::ostream& operator<<(std::ostream& os, Example const& example);
};
#include <iostream>
int main()
{
Example e(123);
std::cout << e << '\n';
}
std::ostream& operator<<(std::ostream& os, Example const& example)
{
os << example.i;
return os;
}
Note that you cannot safely forward-declare standard classes in your own code. Related questions:
Forward declare an STL container?
Forward Declaration of variables/classes in std 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;
}