+ 1
can anyone explain "std::ostream& IntArray<T>::operator<<(std::ostream&, const IntArray<T>&)' must take exactly one argument"
when i implement " ostream& operator<<(ostream& os,const IntArray &d)" ,which is member of class IntArray, outside of class, i write like this template<class T> ostream & IntArray<T>::operator<<(ostream & os, const IntArray<T> & d){...} above error is being reached please help!
5 Respostas
+ 5
Dennis 👍 right answer!
Abrorbek Zukhriddinov as you may have noticed the signature of ostream overload is different in source code...
std::ostream &intArray<T>::operator << This overloads operator << of intArray and not ostream.
In Dennis answer ostream is overloaded properly
+ 3
Are you overloading ostream << operator or IntArray<T> << operator?
Can you provide a piece of code please?
+ 2
You need to make it a friend of IntArray so that it gets access to the private parts of IntArray.
A friend function is not part of the class' member functions therefore IntArray<T>:: is not correct.
Since your class is a template things get a bit more complicated, template friends are a less intuitive/hard part of the language.
The way I usually do it is give the friend function a template as well.
template<typename T>
class IntArray
{
template<typename U> // <-- Can't be template<typename T> as it's already in use
friend std::ostream& operator<<( std::ostream& os, const IntArray<U>& o ); // Notice the <U> and not the <T>
private:
T* a;
int size;
};
template<typename U> // Again, not T
std::ostream& operator<<( std::ostream& os, const IntArray<U>& o )
{
// ...
return os;
}
Reason for it is if you don't template the friend as well and just use T then the compiler will only generate a declaration for IntArray<T> but there is no implementation for it so a linker error will occur.
'IntArray<int> a' would generate
friend std::ostream& operator<<( std::ostream& os, const IntArray<int>& o );
and you would have to specifically implement
std::ostream& operator<<( std::ostream& os, const IntArray<int>& o ){ ... }
Now it works fine for IntArray<int> but breaks with IntArray<unsigned> unless you feel like implementing it for every possible type.
+ 1
yes for sure!
header file:
template<class T>
class IntArray{
public:
/copy cunst..
/ member functions
/destructer
private:
T *a;
int size;
};
template<class T>
std::ostream & operator<<(std::ostream & os, const IntArray<T> & d);
//end of header file
source code//implementattion:
template<cass>
std::ostream &IntArray<T>:: operator<<(std::ostream & os, const IntArray<T> & d){
for(int i=0;i<d,size;i++)
os<<d.a[i]<<std::endl;
return os;
}
i hope it is sufficient to understand the process!
+ 1
Yes thanks for all of you! I got them !