I defined a class `test' and also overloaded the << operator for it. It came out that I can apply cout to objects of test to print the contents to the console, but I got stuck when trying to print them to the console using copy. It'll be a compile-time error when using copy!
Is there anything wrong with my code? Do I need to overload more operators?
Code:#include <algorithm> #include <iostream> #include <iterator> #include <string> #include <vector> using namespace std; class test { friend ostream& operator <<(ostream &out, test &t); public: test(int n) { a = n; } private: int a; }; int main() { vector<test> vec; vec.push_back(1); vec.push_back(2); for ( vector<test>::iterator it = vec.begin(); it != vec.end(); ++it ) { cout << *it << ' '; } // compile-time error when using copy // copy(vec.begin(), vec.end(), ostream_iterator<test>(cout, " ")); cout << endl; } ostream& operator <<(ostream &out, test &t) { return (out << t.a); }



LinkBack URL
About LinkBacks


