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
Related
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;
}
I would like to print a std::unique_ptr which is a class member of Bar.
However, the following code does not work see my comment on stream << bar.foo_unique();
I think I should change my foo_unique() accessor but I don't know how.
#include <iostream>
#include <memory>
class Foo
{
public:
Foo() : n_(1) {}
int n() const { return n_; }
private:
int n_;
};
std::ostream& operator<< (std::ostream& stream, const Foo& foo);
std::ostream& operator<< (std::ostream& stream, const Foo& foo)
{
stream << foo.n();
return stream;
}
class Bar
{
public:
Bar() : m_(2), foo_(), foo_unique_(std::make_unique<Foo>()) {}
int m() const { return m_; }
const Foo& foo() const { return foo_; }
const std::unique_ptr<Foo>& foo_unique() const { return foo_unique_; } // what to return here ?
private:
int m_;
Foo foo_;
std::unique_ptr<Foo> foo_unique_;
};
std::ostream& operator<< (std::ostream& stream, const Bar& bar);
std::ostream& operator<< (std::ostream& stream, const Bar& bar)
{
stream << bar.m() << ",";
stream << bar.foo();
// stream << bar.foo_unique(); // does not work !!!
return stream;
}
int main()
{
Bar bar;
std::cout << bar << std::endl;
}
How can I do that properly ?
edit : I want stream << bar.foo_unique(); to have the same behaviour as stream << bar.foo();
There is no output operator defined for std::unique_ptr<T>: it is a bit sad but many of the C++ classes are lacking output operators. The easiest approach is to just print the pointer:
stream << bar.foo_unique().get();
if you want to get the actually pointer printed or you'd dereference the pointer
stream << *bar.foo_unique();
if you want to get the pointee printed.
To use the output operator you can create your own output operator taking a std::unique_ptr<Foo> assuming Foo is a user-defined type. You'd put it into the same namespace as where Foo is defined:
std::ostream& operator<< (std::ostream& out, std::unique_ptr<Foo> const& foo) {
return out << *foo; // or foo.get()depending on what you want to get printed
}
There is no implicit conversion from std::unique_ptr<T> to T const& which is preventing the stream insertion operator from being determined. You have a couple of options here though. The first option is to provide one override of operator<< for std::unique_ptr<T> and one for T&. This can get tedious if you have use both std::unique_ptr and non-owning raw pointers or references. The second option is to provide a single templated version of operator<< to handle instances of std::unique_ptr<T> and then individual ones to handle T const&. Below is an example of how to accomplish this.
std::ostream& operator<< (std::ostream& out, Foo const& arg)
{
// output stuff here
return out;
}
template<class T>
std::ostream& operator<< (std::ostream& out, std::unique_ptr<T> const& arg)
{
return out << *arg;
}
I have a class MyList that overrides the << operator to be able to log itself to the console:
class MyList {
public:
vector<int> *numbers;
};
ostream& operator<<(ostream& os, MyList& l);
Implementation:
ostream& operator<<(ostream& os, MyList& l) {
for (int i = 0; i < l.numbers->size(); i++) {
os << l.numbers->at(i);
}
return os;
}
In an other class I have a member variable of type MyList and I can't print it to the console. Interestingly a local MyList variable works fine:
class A {
public:
MyList list;
void someMethod() const;
};
Implementation:
void A::someMethod() const {
MyList local;
// Set up local list.
cout << "Local:" << local; // OK!
cout << "Member:" << list; // ERROR!
}
This is the error message:
Invalid operands to binary expression ('basic_ostream<char,
std::__1::char_traits<char>>' and 'const MyList')
Xcode's auto-fix recommends to reference list:
cout << "Member:" << &list;
This will compile, but (obviously) it prints the adress of list and not my content. I don't understand what the difference is between those two variables in regards to the << operator. Could anybody explain?
I don't think this is your real code, but here's my guess:
ostream& operator<<(ostream& os, const MyList& l)
// |
// note const
Either that, or something really dumb like forgetting a trailing ;:
class A {
public:
MyList list;
void someMethod();
}; // <------- here
It seems, you omitted a const in several places: As it stands, your code should be OK. However, if you have a const member function, the members are const and you can't bind a non-const reference to a const object. Thus, output operators are normally declared to take a const& as second argument:
std::ostream& operator<< (std::ostream& os, MyList const& l) {
...
}
Which operator do I have to overload if I want to use sth like this?
MyClass C;
cout<< C;
The output of my class would be string.
if you've to overload operator<< as:
std::ostream& operator<<(std::ostream& out, const MyClass & obj)
{
//use out to print members of obj, or whatever you want to print
return out;
}
If this function needs to access private members of MyClass, then you've to make it friend of MyClass, or alternatively, you can delegate the work to some public function of the class.
For example, suppose you've a point class defined as:
struct point
{
double x;
double y;
double z;
};
Then you can overload operator<< as:
std::ostream& operator<<(std::ostream& out, const point & pt)
{
out << "{" << pt.x <<"," << pt.y <<"," << pt.z << "}";
return out;
}
And you can use it as:
point p1 = {10,20,30};
std::cout << p1 << std::endl;
Output:
{10,20,30}
Online demo : http://ideone.com/zjcYd
Hope that helps.
The stream operator: <<
You should declare it as a friend of your class:
class MyClass
{
//class declaration
//....
friend std::ostream& operator<<(std::ostream& out, const MyClass& mc);
}
std::ostream& operator<<(std::ostream& out, const MyClass& mc)
{
//logic here
}
You should implement operator<< as a free function.
Given a class such as:
class Person
{
private:
char *name;
public:
Person()
{
name = new char[20];
}
~Person()
{
delete [] name;
}
}
I want to print to print the name from an instance of this, using a statement like the following:
cout << myPerson << endl;
What do I need to do to define the << output operator for this class?
add this in the class:
friend std::ostream& operator<< (std::ostream& out, const Person& P);
and then define the operator<< something like this:
std::ostream& operator<< (std::ostream& out, const Person& P) {
out << P.name;
return out;
}
Define a member function print() that takes an ostream as an argument. Then let the overloaded operator<< call this member function. This way you can avoid using friend. Example:
void YourClass::print(ostream& out) const
{
//implement printing ...
}
ostream& operator<<(ostream& out, const YourClass& m)
{
m.print(out);
return out;
}