템플릿 링크드 목록 (.h 파일)을 프로그래밍했는데 링크 오류가 발생합니다.템플릿 링크드 목록에서 친구 기능을 사용할 때 링크 오류가 발생했습니다.
template <typename T> friend ostream& operator << (ostream& out, const LinkedList<T>& that);
템플릿 링크드 목록 (.h 파일)을 프로그래밍했는데 링크 오류가 발생합니다.템플릿 링크드 목록에서 친구 기능을 사용할 때 링크 오류가 발생했습니다.
template <typename T> friend ostream& operator << (ostream& out, const LinkedList<T>& that);
다음은 일입니다. 이
template <typename U> //or T, doesn't matter
friend ostream& operator << (ostream& out, const LinkedList<U>& that);
같은 친구를 선언하면
는 operator << <int>
는 LinkedList<float>
의 친구가 될 것입니다. 즉 바람직하지 않은 경우,이 솔루션이 :
friend ostream& operator <<<T> (ostream& out, const LinkedList<T>& that);
이 경우, 템플릿의 특정 인스턴스는 당신이 필요 수 있습니다 당신의 친구입니다.
감사합니다! 지금은 이해. – geniaz1
클래스 외부 operator<<
의 정의 실제로 함수이기 때문에 : 나는 수업 시간에 친구 함수의 선언에 대신 쓸 때
template <typename T>
class LinkedList
{
private:
Node<T>* head;
Node<T>* tail;
int size;
public:
LinkedList();
~LinkedList();
inline T* Front() {return &(this->head);};
inline const T* Front() const {return (const T*)this->head;};
void InsertFirst(const T&);
void InsertLast(const T&);
void RemoveFirst();
void RemoveLast();
void RemoveItem (const T&);
void Sort();
void Clear();
inline bool Exists(const T&) const;
bool Empty() const {return this->size==0 ? true : false;};
inline int Size() const {return this->size;};
T* At(const int index);
const T* At(int index) const;
friend ostream& operator << (ostream& out, const LinkedList<T>& that);
T* operator[](const int);
const T* operator[](const int) const;
};
.
.
.
template <typename T>
ostream& operator << (ostream& out, const LinkedList<T>& that)
{
if (!that.Empty())
for(Node<T>* seeker=that.head; seeker; seeker=seeker->next)
out<<seeker->info<<endl;
return out;
}
은 어떤 이유로 링크 오류가 사라 클래스 내에있는 friend 선언은 함수 템플릿이 아닙니다.
friend
선언은 템플릿이 아닌 함수이며 해당 인수는 클래스 템플릿과 관련하여 고정되어 있습니다. "나는이 클래스의 친구 해요 컴파일러를 알려줍니다
friend ostream& operator << (ostream& out, const LinkedList<int>& that);
, 나는 또한 해요 : 당신이 int
와 클래스 템플릿을 인스턴스화하는 경우
예를 들어, 다음 friend
이된다 템플릿이 아닌 기능을 사용하면 클래스 외부에서 내 서명을 찾을 수 있습니다. " 인수가 수정 된 것을 볼 수 있습니다.
그러나 당신은 이런 식으로 뭔가를 할 때
template <typename U>
friend ostream& operator << (ostream& out, const LinkedList<U>& that);
그것도 함수 템플릿입니다 클래스 외부 operator<<
의 정의와 일치으로 그것은 컴파일러에 의미가 있습니다. 그러나 문제가 있습니다. 그것은 함수 템플릿의 모든 전문화를 클래스의 친구로 만듭니다. U=float
일 때 operator<<
은 LinkedList<int>
의 개인 회원도 액세스 할 수 있으며, LinkedList<float>
전용 회원에게만 액세스 할 수 있어야합니다. 보시다시피, 이것이 문제입니다.
더 나은 해결책은 다음과 같습니다. 기능 템플릿을 만들지 말고 클래스 자체 내에 친구를 정의하십시오. 당신이 선언 된 친구가 서식하지 않습니다, 그래서 당신의 < < 템플릿의 주어진 인스턴스는 친구가 선언 된 것이 아니다 :
template<typename T>
class LinkedList
{
public:
friend ostream& operator << (ostream& out, const LinkedList<T>& that)
{
//definition
}
};
당신이 자신을 대답 것 같은데 구체적으로 항목을 설명합니다 ... – user1071136