Reputation: 131
Hey guys I am new to C++ and I have a problem with this operator: (Also new in stackoverflow)
This is my class TestList:
class TestList{
public:
TestList() : listItems(10), position(0){};
TestList(int k) : listItems(k), position(0){};
int listItems;
int position;
std::vector<int> arr;
};
//my current operator is: What should be changed?
ostream& operator <<(ostream&, const TestList& tlist, int input){
os << tlist.arr.push_back(input);
return os;
}
//
int main() {
testList testlist(5);
testlist << 1 << 2 << 3; //how should I overload the operator to add these number to testlist.arr ?
return 0;
}
I hope someone could help me or can give me any tips? :)
Upvotes: 1
Views: 88
Reputation: 310920
I think you mean the following
TestList & operator <<( TestList &tlist , int input )
{
tlist.arr.push_back( input );
return tlist;
}
Here is a demonstrative program
#include <iostream>
#include <vector>
class TestList{
public:
TestList() : listItems(10), position(0){};
TestList(int k) : listItems(k), position(0){};
int listItems;
int position;
std::vector<int> arr;
};
TestList & operator <<( TestList &tlist , int input )
{
tlist.arr.push_back( input );
return tlist;
}
std::ostream & operator <<( std::ostream &os, const TestList &tlist )
{
for ( const auto &item : tlist.arr )
{
std::cout << item << ' ';
}
return os;
}
int main()
{
TestList testlist(5);
testlist << 1 << 2 << 3;
std::cout << testlist << '\n';
return 0;
}
The program output is
1 2 3
You can even write instead of these two statements
testlist << 1 << 2 << 3;
std::cout << testlist << '\n';
only one statement
std::cout << ( testlist << 1 << 2 << 3 ) << '\n';
Pay attention to that there is a typo in your declaration
testList testlist(5);
There should be
TestList testlist(5);
Upvotes: 0
Reputation: 5075
The other answers are absolutely correct, I just want to say something general on operator<<
. It always has the signature T operator<<(U, V)
, since it is always a binary operator, so it has to have exactly two arguments. Since the chain
a << b << c;
is evaluated as
(a << b) << c;
// That calls
operator<<(operator<<(a, b), c);
the types T
and U
should normally be the same, or at least compatible.
Furthermore, it is possible but very weird to assign the result of operator<<
to something (like result = (a << b)
)). A good rule of thumb is "My code should not be weird". Therefore the type T
should mostly be a reference (so X&
) since otherwise it would only be a temporary copy that is unused. And that is pretty useless most of the time.
So in 90% of all cases, your operator<<
should have the signature
T& operator<<(T&, V);
Upvotes: 1