让
Foo.hpp:
void Foo::print() const
{
copy(bar_.begin(), bar_.end(), ostream_iterator<Bar<string, int>*>(cout, "\n"));
}
Bar.hpp:
template <typename Key, typename T>
ostream& operator<<(ostream& out, const Bar<Key, T>& bar)
{
return out << "FOOBAR";
}
其中bar_是Foo的属性,是Bar元素的向量。假设bar_有一个元素,然后输出:
Foo foo;
foo.print();
是bar_中元素的地址,而不是“FOOBAR”。为什么呢?
声明:
class Foo
{
public:
void print() const;
protected:
vector<Bar<string, int>*> bar_;
};
class Bar
{
public:
template <typename K, typename U>
friend ostream& operator<<(ostream&, const Bar<K, U>&);
}