开发者

Outputing an object through a template class member function

I'm trying to use a simple output function of the class template indexedList with an object of a simple class. I've overloaded the output operator in the class as a friend function as follows:

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

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

It works fine on its own, but when I try to use it with the class template indexedList the compiler gives an error. Here is the output function in the class template:

//in header file
void display() const;  

//in implementation file
void indexLi开发者_如何学Gost<T, maxSize>::display() const{
for (int i = 0; i < size; i++)
    cout << elements[i] << endl;
}

In the driver, I simply append a few objects of simpleClass into the "elements" array of a simpleClass indexedList, and try to use the display() function. This is the only error message I get:

"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.

Both the class template and the simple class work well on their own but combining them does not. Any help would be greatly appreciated!


Not familiar with 'indexList', but as display() is a const method, elements[i] is likely returning a const simpleClass &, and thus you're trying to drop the const qualifier in your call to operator << ().

Try having operator << () take a const reference.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜