We have the following situation:
In Classes A and B, we have overridden the << operator.
Now, we have a new class C with data members of objects of A and B.
How would we override the << operator here?
To be more specific,
We need something like this:
cout<<objectOfC corresponds to cout<<correspondingObjectOfA<<correspondingObjectOfB
I'm not getting how to modify the ostream& object so as to return it back.
ostream& operator<< (ostream& out, const C& obj){ // This is a friend function declared in C.h
A* a = obj.AObject; // Returns the corresponding object of A
B* b = obj.BObject; // Returns the corresponding object of B
// Need to modify out somehow to 'cout' A and B respectively when cout is called on an object of C
return out;
}
Any help would be greatly appreciated. Thank you :)
If you already have appropriate overrides for A and B, just use them.
ostream& operator<< (ostream& out, const C& obj) {
out << *obj.AObject << *obj.BObject;
return out;
}
Because operator<< returns its ostream argument, you can further condense this:
ostream& operator<< (ostream& out, const C& obj) {
return out << *obj.AObject << *obj.BObject;
}
Related
I have the following class template which will accept both primitives and object. However like this I can only print primitives. How can I make it function using both primitives and objects? Thanks
template<class T>
class A
{
private:
vector <T> l;
public:
void print() const
{
for (int i=0;i<.size();i++)
{
cout<<l[i]<<endl; //error here
}
}
};
The reason why you can print primitives is that <iostream> provides overloads for operator<< for them.
To let your template print your classes in the same way, you need to define your own implementation of the operator:
// This implementation puts operator << outside your class.
// Mark it "friend" in MyClass if it needs access to private members of MyClass.
ostream& operator<<(ostream& ostr, const MyClass& myClass) {
// Do the printing based on the members of your class
ostr << myClass.member1 << ":" << myClass.member2;
return ostr;
}
The compiler will detect this operator during template expansion, and use it for printing when you do this:
cout<<l[i]<<endl;
You can put operator<< inside your class as well:
ostream &operator<<(ostream &os) {
ostr << member1 << ":" << member2;
}
I am assuming that here, you want to print an object instead of a variable belonging to a fundamental datatype.
For such cases, you can look at operator overloading in C++(more specifically overloading insertion operator).
For more information about overloading the insertion operator for an object, you can visit this URL
http://msdn.microsoft.com/en-us/library/1z2f6c2k.aspx
Given below is an example about how to go about it
ostream& operator<<(ostream& os, const Datatype& dt)
{
os << dt.a <<" " << dt.b;
return os;
}
Here Datatype is the name of the class and a and b are two private members of a and b which will be printed when you try to print the object.
However, to overload using this technique, do not forget to make this function as a friend function of the class(as given below) as the function requires access the to private members of the class.
friend ostream& operator<<(ostream& os, const Datatype& dt);
I have a slight problem where my << operator is not being called correctly.
This is what I have:
class SomeInterface
{
friend std::ostream& operator<<(std::ostream& str, const SomeInterface& data);
protected:
virtual void print(ostream& str) const = 0;
};
inline std::ostream& operator<< (std::ostream& o, SomeInterface const& b)
{
b.print(o);
return o;
}
}
Calling code looks something like:
SomeInterface* one = new someConcrete ();
cout << one;
The << overloaded function I was hoping would get called on the interface is not, let alone dispatching through to the derived class.
Try:
cout << *one;
Your code is asking to print the pointer, while your operator<< takes a const SomeInterface& reference.
You are calling std::ostream& operator<< (std::ostream& o, void*);, because the type of one is a pointer.
Try:
cout << *one;
This will call the overload that takes a (reference to) the actual object, not the pointer itself
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Operator overloading
I didn't find any thing that could help me in this subject...
I'm trying to over load the << operator, this is my code:
ostream& Complex::operator<<(ostream& out,const Complex& b){
out<<"("<<b.x<<","<<b.y<<")";
return out;
}
this is the declaration in the H file:
ostream& operator<<(ostream& out,const Complex& b);
I get this error:
error: std::ostream& Complex::operator<<(std::ostream&, const Complex&) must take exactly one argument
what and why I'm doing wrong?
thanks
your operator << should be free function, not Complex class member in your case.
If you did your operator << class member, it actually should take one parameter, which should be stream. But then you won't be able to write like
std::cout << complex_number;
but
complex_number << std::cout;
which is equivalent to
complex_number. operator << (std::cout);
It is not common practice, as you can note, that is why operator << usually defined as free function.
class Complex
{
int a, b;
public:
Complex(int m, int d)
{
a = m; b = d;
}
friend ostream& operator<<(ostream& os, const Complex& complex);
};
ostream& operator<<(ostream& os, const Complex& complex)
{
os << complex.a << '+' << complex.b << 'i';
return os;
}
int main()
{
Complex complex(5, 6);
cout << complex;
}
More info here
As noted, the streaming overloads need to to be free functions, defined outside of your class.
Personally, I prefer to stay away from friendship and redirect to a public member function instead:
class Complex
{
public:
std::ostream& output(std::ostream& s) const;
};
std::ostream& operator<< (std::ostream& s, const Complex& c)
{
return c.output(s);
}
hey, i got something that i cannot understand ,there are two types of solutions for overloading this operator 1 is including the friend at the start of the method and the other 1 goes without the friend.
i would very much like if some1 explain whats the difference between them advantages / disadvantages.
for example overloading the operator << in class rational:
class Rational:
{
private: int m_t,m_b;
...
friend ostream& operator<<(ostream& out,const Rational& r) // option 1
{ return out << r.m_t << "/" <<r.m_b;} // continue of option 1
ostream& operator<<(ostream& out,const Rational& r){return r.print();} // option 2
virtual ostream& print(ostream& out) const // continue of option 2
{ //
return out<<m_t << "/" << m_b;
} //
};
i was told that the second option isnt correct , if some1 can correct me about it i would much appriciate it.
thanks in advance.
The short answer: Option #2 actually isn't an option, but a syntax error, because it tries to define a binary operator as a member passing two operands.
The somewhat longer answer: If you make the second operand a free function (not a member of the class), this will work. Which one is preferable depends on the circumstances and your preferences. For starters: The disadvantage of the first is that it allows operator<< to access everything in Rational (including private helper functions), while the disadvantage of the second is that you introduce a function to the class' public API that nobody needs.
operator<< (for ostream) needs to be a free function (since the left-hand argument is a stream, not your class).
The friend keyword makes it a free function (a free function that has access to the private members).
However, if this functionality can be implemented in terms of the public interface, it is better to do so and just use a non-friend free function.
class Rational:
{
private: int m_t,m_b;
public:
...
virtual ostream& print(ostream& out) const
{
return out<<m_t << "/" << m_b;
}
};
ostream& operator<<(ostream& out,const Rational& r)
{
return r.print(out);
}
Consider a function that should output the num and den of Rational:
ostream& operator<<(ostream& out, const Rational& r)
{
return out;
}
Unfortunately, this is just a global function. Like any other global function, it cannot access the private members of Rational. To make it work with Rational objects, you need to make it friend of Rational:
class Rational
{
private: int m_t,m_b;
// ...
friend ostream& operator<<(ostream& out, const Rational& r);
};
ostream& operator<<(ostream& out, const Rational& r)
{
out << r.m_t << "/" <<r.m_b;
return out;
}
The friend ostream& operator<<(ostream& out, const Rational& r); inside Rational class indicates that ostream& operator<<(ostream& out, const Rational& r) function can directly use Rational's private members.
Now when you write:
Rational r(1, 2); // Say, it sets num and den
cout << r;
the following function call is made:
operator<<(cout, r);
Can you write operator<< as a member function of Rational? That's simply not possible because of the above conversion where cout has to be first parameter. If you make operator<< as a member of Rational:
class Rational
{
private: int m_t,m_b;
// ...
public:
ostream& operator<<(ostream& out) const
{
out << r.m_t << "/" <<r.m_b;
return out;
}
};
you need to call it this way:
Rational r(1, 2);
r.operator<<(cout);
which is ugly.
Im really unsure how to call the function:
friend ostream& operator<<(ostream& out, stack::myItem& theItem);
that is public to my stack object:
class stack
{
public:
stack(int capacity);
~stack(void);
void method1();
...
private:
struct myItem
{
int item;
};
...
public:
friend ostream& operator<<(ostream& out, stack& s);
friend ostream& operator<<(ostream& out, stack::myItem& theItem);
};
It's no different than using stream operator << for any other type (it is called operator overloading for a reason).
However, outputting should not modify an object, hence you really should pass it by const reference (otherwise calls with temporaries would fail to compile).
friend ostream& operator<<(ostream& out, const stack& s);
friend ostream& operator<<(ostream& out, const stack::myItem& theItem);
This operator is a classic binary operator.
// Say I have an operator declared like this:
return_type operator#(left_type lhs, right_type rhs);
// Then the invocation is done this way:
left_type L;
right_type R;
return_type result = L # R;
In the case of the streaming operator, it is a bit special since the left hand argument and the return type actually have the same type (and indeed, will refer to the same object, albeit at different times). This has been done to allow chaining.
// Chaining
std::cout << "<Output> " << 1 << std::endl;
// Which can be analyzed like such
operator<<(
operator<<(
operator<<(
std::cout ,
"<Output> "
),
1
),
std::endl
);
As you can see, the syntax merely allows a convenient invocation. One might note that the order is very well defined, it is a strict left to right evaluation.
So with your object, it would become:
stack s;
std::cout << s << std::endl;
Just like that!
Call it from where? As it's coded only the class knows about the private struct. No code external to the class could use that method since it couldn't create an instance of the struct. Marking it as friend doesn't do you much good.