寫單向鏈表實現(xiàn)線性表的時候打算重載輸出運算符用來將線性表輸出,結果無奈又遇到了問題。
大致代碼如下
運行的時候編譯器報錯說 無法解析的外部符號
想來想去也只能使友元函數出了問題,于是果斷百度了解了一下
友元函數雖然可以訪問類內部的成員,但是它相對于類是獨立的,它的實現(xiàn)不能依賴類。代碼中用到模板類template
解決方法有兩個
第一種:可以將友元函數的實現(xiàn)放在類的內部
第二種:在類的內部聲明友元函數的時候在之前為它單獨配一個模板類型,然后在外部實現(xiàn)
template<class T>
class chainList : public linearList<T>
{
template<typename U>
friend ostream& operator<<(ostream & out, const chainList<U> & rhs);
public:
......
private:
......
};
//友元函數實現(xiàn)的實現(xiàn)
template<typename U>
ostream & operator<<(ostream & out, const chainList<U> & rhs)
{
......
}
模板類中的友元函數需要進行特別的處理,參考
#ifndef ARRAY_H
#define ARRAY_H
#include <iostream>
#include <iomanip>
using namespace std;
//模板類前置聲明
template<class T>
class Array;
//Array模板類的友元聲明
template<class T>
istream& operator>>(istream& input, Array<T>& a);
template<class T>
ostream& operator<<(ostream& output, const Array<T>& a);
template<class T>
class Array{
friend ostream& operator<< <> (ostream&, const Array<T>&);
friend istream& operator>> <> (istream&, Array<T>&);
public:
Array(int arraySize = 10){
size = (arraySize > 0 ? arraySize : 10);
ptr = new T[size];
for (int i = 0; i < size; i++)
ptr[i] = 0;
}
Array(const Array &arrayToCopy){
ptr = new int[size];
for (int i = 0; i < size; i++){
ptr[i] = arrayToCopy[i];
}
}
~Array(){
delete[] ptr;
}
int getSize()const{
return size;
}
const Array& operator=(const Array &right){
if (&right != this){
if (size != right.size){
delete[] ptr;
size = right.size;
ptr = new T[size];
}
for (int i = 0; i < size; i++)
ptr[i] = right.ptr[i];
}
return *this;
}
bool operator==(const Array &right)const{
if (size != right.size)
return false;
for (int i = 0; i < size; i++)
if (ptr[i] != right.ptr[i])
return false;
return true;
}
bool operator!=(const Array &right)const{
return !(*this == right);
}
T& operator[](int subscript)
{
if (subscript < 0 || subscript >= size){
cerr << "\nError: Subscript " << subscript
<< "out of range" << endl;
exit(1);
}
return ptr[subscript];
}
T operator[](int subscript)const{
if (subscript < 0 || subscript >= size)
{
cerr << "\nError: Subscript" << subscript
<< "out of range" << endl;
exit(1);
}
return ptr[subscript];
}
private:
int size;
T *ptr;
};
#endif
template<class T>
istream& operator>>(istream &input, Array<T> &a){
for (int i = 0; i < a.size; i++)
input >> a.ptr[i];
return input;
}
template<class T>
ostream& operator<<(ostream &output, const Array<T> &a){
int i;
for (i = 0; i < a.size; i++){
output << setw(12) << a.ptr[i];
if ((i + 1) % 4 == 0)
output << endl;
}
if (i % 4 != 0)
output << endl;
return output;
}