#include <iostream>
using namespace std;
template <class Type> class Queue;
template <class Type>
class QueueItem {
friend class Queue<Type>;
friend ostream&
operator<< ( ostream &os, const QueueItem<Type> &qi );
friend ostream&
operator<< ( ostream &os, const Queue<Type> &q );
public:
QueueItem(const Type &a ){item=a;next=0;}
private:
Type item;
QueueItem *next;
};
//
template <class Type>
class Queue {
friend ostream&
operator<< ( ostream &, const Queue<Type> & );
public:
Queue() : front( 0 ), back ( 0 ) { }
~Queue();
Type remove();
void add( const Type & );
bool is_empty() const
{
return front == 0;
}
//private:
QueueItem<Type> *front;
QueueItem<Type> *back;
};
//
template <class Type>
Queue<Type>::~Queue()
{
while ( ! is_empty() )
remove();
}
//
template <class Type>
void Queue<Type>::add( const Type &val )
{
// 分配新的 QueueItem 对象
QueueItem<Type> *pt =new QueueItem<Type>( val );
if ( is_empty() )
front = back = pt;
else
{
back->next = pt;
back = pt;
}
}
//
template <class Type>
Type Queue<Type>::remove()
{
if ( is_empty() )
{
cerr << "remove() on empty queue \n";
exit( - 1 );
}
QueueItem<Type> *pt = front;
front = front->next;
Type retval = pt->item;
delete pt;
return retval;
}
//
template <class Type> ostream&
operator<< ( ostream &os, const Queue<Type> &q )
{
os << "< ";
QueueItem<Type> *p;
for ( p = q.front; p; p = p->next )
os << *p << " ";
os << " >";
return os;
}
//
template <class Type>ostream&
operator<< ( ostream &os, const QueueItem<Type> &qi )
{
os << qi.item;
return os;
}
//
int main() {
Queue<int> qi;
// 实例化两个实例:
// ostream& operator<< (ostream &os, const Queue<int> &)
// ostream& operator<< (ostream &os, const QueueItem<int> &)
cout << qi << endl;
int ival;
for ( ival = 0; ival < 10; ++ival )
qi.add( ival );
cout << qi << endl;
int err_cnt = 0;
for ( ival = 0; ival < 10; ++ival ) {
int qval = qi.remove();
if ( ival != qval ) err_cnt++;
}
cout << qi << endl;
if ( !err_cnt )
cout << "!! queue executed ok\n";
else cout << "<<<< queue errors: " << err_cnt << endl;
return 0;
}
/* VC6下编译错误信息如下:
--------------------Configuration: p-685 - Win32 Debug--------------------
Compiling...
p-685.cpp
G:\lc\p-685.cpp(102) : error C2248: 'item' : cannot access private member declared in class 'QueueItem<int>' G:\lc\p-685.cpp(20) : see declaration of 'item'
G:\lc\p-685.cpp(93) : see reference to function template instantiation 'class std::basic_ostream<char,struct std::char_traits<char> > &__cdecl operator <<(class std::basic_ostream<char,struct std::char_traits<char> > &,const class QueueItem<
int> &)' being compiled
Error executing cl.exe.
p-685.exe - 1 error(s), 0 warning(s)
*/
应该 怎样改呢?
请各位帮忙解释一下,谢了!
參考答案:你的VC6.0没有打上SP5或SP6补丁,这是VC6.0的一个bug