簡體   English   中英

鏈接模板類的友元函數中的錯誤

[英]linking error in friend function of a template class

我有模板類節點,為了遵循復制和交換習慣用法,我嘗試編寫swap函數,這是類Nodefriend

我的代碼是:

Node.h

#ifndef NODE_H
#define NODE_H

#include<memory>
template<typename type>
class Node
{
    type data_;
    std::unique_ptr<Node> next_;
public:
    Node(type data);
    Node(const Node& other);
    Node& operator=(Node other);
    friend void swap(Node& lhs, Node& rhs);
};

#include "Node.tpp"
#endif

Node.tpp

template<typename type>
Node<type>::Node(type data):data_(data),next_(nullptr){
}

template<typename type>
Node<type>::Node(const Node& other)
{
    data_ = other.data_;
    next_ = nullptr;
    if(other.next_ != nullptr)
    {
        next_.reset(new Node(other.next_->data_));
    }
}
template<typename type>
void swap(Node<type>& lhs, Node<type>& rhs)
{
    using std::swap;
    swap(lhs.data_,rhs.data_);
    swap(lhs.next_,rhs.next_);
}

template<typename type>
Node<type>& Node<type>::operator=(Node other)
{
    swap(*this,other);
    return *this;
}

當我從Source.cpp測試它

#include "Node.h"
int main()
{
    Node<int> n(3);
    Node<int> n2(n);
    Node<int> n3(5);
    n3 = n2;
}

我收到以下鏈接錯誤

LNK2019: unresolved external symbol "void __cdecl swap(class Node<int> &,class Node<int> &)

友元聲明不“繼承”模板參數,但需要自己的:

template<typename type>
class Node
{
    // ...
public:
    // ...
    template<typename U> // <<<<<<<<<<<
    friend void swap(Node<U>& lhs, Node<U>& rhs);
                      // ^^^           ^^^
    // ...
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM