2011-03-22 130 views
1

我正在尝试使用简单类的对象的类模板indexedList的简单输出函数。我重载类中的输出操作为好友功能如下:通过模板类成员函数输出一个对象

//in header file 
friend ostream& operator <<(ostream&, simpleClass&); 

//in implementation file 
ostream& operator <<(ostream& out, simpleClass& c1){ 
out << c1.stringDataMem;    
return out; 
} 

它适用于自己的罚款,但是当我尝试使用类模板indexedList编译器使用它给出了一个错误。下面是在类模板的输出功能:

//in header file 
void display() const; 

//in implementation file 
void indexList<T, maxSize>::display() const{ 
for (int i = 0; i < size; i++) 
    cout << elements[i] << endl; 
} 

在驱动程序,我简单simpleClass的几个对象追加到一个simpleClass indexedList的“元素”阵列,并尝试使用所述显示器()函数。这是唯一的错误信息获取:

"IndexList.cpp", line 38: Error: Formal argument 2 of type simpleClass& in call 
to_operator<<(std::basic_ostream<char, std::char_traits<char>>&, simpleClass&) 
requires an lvalue. 

两个类模板和简单类的工作以及自己的,但结合他们没有。任何帮助将不胜感激!

回答

1

不熟悉“indexList”,但作为显示器()是一个const方法,元素[i]是有可能返回常量 simpleClass &,因此你想在你的电话砸const限定运营商< <()。

尝试运算符< <()取一个const引用。

+0

非常好,完美的作品。现在我可以生气地说我的编译器提供了有关不断引用的内容......谢谢! – ghudner 2011-03-22 02:46:38