template <class ElementType,int Dimension=1>
class Vector : public vector<ElementType> {
public:
Vector & operator+= (const Vector & a){
cout << " a " << a << endl;
transform (this->begin(), this->end(), a.begin(), this->begin(), plus<ElementType>());
return *this;
};
friend ostream & operator<< (ostream & stream, Vector t) {
stream << "(";
copy (t.begin(), t.end()-1, ostream_iterator<ElementType>(stream,","));
return stream << *(t.end()-1) << ")";
};
};
1) During runtime I get the error message:
terminate called after throwing an instance of 'std::bad_alloc'
what(): std::bad_alloc
I've found that this message is caused by cout << " a " << a << endl;
2) Without that cout << ..... operation finished successfully but some garbage is added to this instead of contents of a.
Any suggestions?
There exists std::valarray for this purpose.
This output operator
friend ostream & operator<< (ostream & stream, Vector t)
can possibly cause a bad_alloc because it copies the Vector parameter.
You can try this instead
friend ostream & operator<< (ostream & stream, const Vector& t)
to avoid that.
To avoid the problem with an empty vector not having an end()-1 you might want to put the output inside an if (!t.empty()).
And finally this expression *(t.end()-1) can be simplified to t.back().
Related
I am writing this code
ostream& operator <<(ostream& out, Box& B){
return B.l +" "+B.b +" "+B.h +endl;
};
The error I get is
Solution.cpp:40:46: error: ‘std::ostream& Box::operator<<(std::ostream&, Box&)’ must have exactly one argument ostream& operator <<(ostream& out, Box& B){ ^
can someone explain what's wrong? I dont understand.
thanks for your help :)
It seems you mean the following
std::ostream & operator <<( std::ostream& out, const Box& B) {
return out << B.l << " " << B.b << " " << B.h;
}
provided that all used in the operator data members are public data members of the class Box. The operator shall be declared and defined outside the class definition.
If one of the used data members is a private data member of the class then the function should be a friend function of the class and shall be declared (and may be defined) in the class definition. For example
class Box
{
//...
friend std::ostream & operator <<( std::ostream& out, const Box& B) {
return out << B.l << " " << B.b << " " << B.h;
}
//...
};
Pay attention to that it is better to remove in the return statement the operand std::endl. In this case 1) the operator will be more flexible because you can output additional information in the same line and 2) this statement
std::cout << box;
will not confuse readers of the code because they will not see the operand std::endl.
Without this operand in the operator definition in the caller of the operator you can write
std::cout << box << std::endl;
and this statement more clear expresses the intention of the programmer.
It should probably be:
std::ostream& operator<<(std::ostream& out, Box const& B){
out << B.l << " " << B.b << " " << B.h << std::endl;
return out;
};
Full code should look like:
#include <iostream>
class Box {
int l;
int b;
int h;
friend std::ostream& operator<<(std::ostream& out, Box const& B);
};
std::ostream& operator<<(std::ostream& out, Box const& B){
out << B.l << " " << B.b << " " << B.h << std::endl;
return out;
}
int main() {
return 0;
}
Demo
To output a type T to std::ostream, you have to declare standalone operator, which returns reference to that stream
std::ostream& operator<<(std::ostream& out, const T& B)
{
out << B.l << " " << B.b << " " << B.h << '\n';
return out;
}
This operation cannot be member operator because member operator use their class as first argument, therefore it might be necessary declare it as a friend of class T.
Avoid using endl in such operators if not extremely necessary, that manipulator calls out.flush(). If you want new line added, use new-line character.
I have created a constructor
Location(double xIn,double yIn,string placeIn,int timeIn)
: x(xIn),y(yIn) ...so on {
Say I want to print Location home(x,y,place,time); that's in the main().
How would I do so? I've been searching around and was told to use operator<<. How would I implement this?
UPDATE: After creating some get methods and I tried doing,can't exactly compile it because of the problem
ostream &operator<<(ostream & o, const Location & rhs){
o << rhs.getX() << "," << rhs.getY() << "," << rhs.getPlace() << "," << rhs.getTime();
return o; }
Here is the stencil for overloading operator<<:
class Any
{
public:
friend std::ostream& operator<<(std::ostream& output, const Any& a);
private:
int member;
};
std::ostream&
operator<<(std::ostream& output, const Any& a)
{
output << a.member;
return output;
}
This one possible stencil, there are other possibilities. Search the internet for "c++ stream insertion operator overload example" for other implementations.
I am working with operator overloads for the first time and am setting up the overload for the extraction operator (<<). I'm stuck in one of two errors that are preventing me from continuing. The code is as follows:
ostream &operator << (ostream &output, const Distance &d1)
{
if (d1.miles > 0)
{
output << d1.miles << "m ";
}
if (d1.yards > 0)
{
output << d1.yards << "y ";
}
if (d1.feet > 0)
{
output << d1.feet << "\' ";
}
output << d1.inches << "\"";
return (output);
}
The overload is declared as a friend in the header file as follows:
friend ostream &operator<< (ostream output, const Distance &d1);
The first issue I encounter is that when the overload is formatted this way (which is as far as I can tell, the correct way) it does not allow me to access the miles, yards, feet, or inches member data, despite the function being set as a friend in the header file.
If I change the overload to read :
ostream &operator << (ostream output, const Distance &d1)
{
if (d1.miles > 0)
{
output << d1.miles << "m ";
}
if (d1.yards > 0)
{
output << d1.yards << "y ";
}
if (d1.feet > 0)
{
output << d1.feet << "\' ";
}
output << d1.inches << "\"";
return (output);
}
Then the overload works correctly, but it does not work in my main function as it returns the error:
error C2248: 'std::basic_ostream<_Elem,_Traits>::basic_ostream' : cannot access private member declared in class 'std::basic_ostream<_Elem,_Traits>'
for every instance of cout in the function. Plus, the previous examples I have show that this would be incorrect. What am I doing wrong in the first code example that is preventing me from accessing the private member data? I've looked at several other instances of this being asked on various sites, but nothing quite matches what I am getting. I have tried compiling with Visual Studio Express 2012 and g++, both return the error.
The declaration inside the class definition should be:
friend ostream &operator<< (ostream &output, const Distance &d1);
// ^--- important
The error in your first attempt is because when you write a function ostream &operator<< (ostream &output, const Distance &d1), this is not the same function you friended because it has different arguments.
The second attempt should have various errors , as it is not permitted to pass ostream by value.
So I have a map like this:
map<long, MusicEntry> Music_Map;
MusicEntry contains strings of (name, artist, size, and date added)
My question is how can print, how do I print out all the data in my map? I have tried doing...
for(auto it = Music_Map.cbegin(); it!= Music_Map.cend(); ++it)
cout << it-> first << ", " << it-> second << "\n";
I think the problem is occuring that it can't compile and read second aka MusicEntry..
You need to provide an std::ostream operator<< (std::ostream&, const MusicEntyr&) so that you can do this kind of thing:
MusicEntry m;
std::cout << m << std::endl;
With that in place, you can print the map's second fields. Here's a simplified example:
struct MusicEntry
{
std::string artist;
std::string name;
};
std::ostream& operator<<(std::ostream& o, const MusicEntry& m)
{
return o << m.artist << ", " << m.name;
}
The code you have is fine, but you need to implement
std::ostream& operator<<(ostream& os, const MusicEntry& e)
{
return os << "(" << e.name << ", " << ... << ")";
}
and you probably need to declare the above a friend in MusicEntry to access the private (or protected) data of MusicEntry:
class MusicEntry
{
// ...
friend std::ostream& operator<<(ostream& os, const MusicEntry& e);
};
This is, of course, not needed if the data is public or if you use public getters. You can find a lot more information in the operator overloading FAQ.
I want to overload the << operator for my class Complex.
The prototype is the following:
void Complex::operator << (ostream &out)
{
out << "The number is: (" << re <<", " << im <<")."<<endl;
}
It works, but I have to call it like this: object << cout for the standart output.
What can I do to make it work backwards, like cout << object?
I know that the 'this' pointer is by default the first parameter sent to the method so that's why the binary operator can work only obj << ostream. I overloaded it as a global function and there were no problems.
Is there a way to overload the << operator as a method and to call it ostream << obj?
I would just use the usual C++ pattern of free function. You can make it friend to your Complex class if you want to make Complex class's private data members visible to it, but usually a complex number class would expose public getters for real part and imaginary coefficient.
class Complex
{
....
friend std::ostream& operator<<(std::ostream &out, const Complex& c);
private:
double re;
double im;
};
inline std::ostream& operator<<(std::ostream &out, const Complex& c)
{
out << "The number is: (" << c.re << ", " << c.im << ").\n";
return out;
}
You could write a free stand operator<< function, try:
std::ostream& operator<< (std::ostream &out, const Complex& cm)
{
out << "The number is: (" << cm.re <<", " << cm.im <<")." << std::endl;
return out;
}
You can define a global function:
void operator << (ostream& out, const Complex& complex)
{
complex.operator<<(out);
}