【问题标题】:linking error in friend function of a template class模板类的友元函数中的链接错误
【发布时间】:2017-04-10 12:08:25
【问题描述】:

我有模板类节点,为了遵循copy-and-swap 习惯用法,我尝试编写swap 函数,它是friend 类Node

我的代码是:

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> &)

【问题讨论】:

    标签: c++ copy-and-swap


    【解决方案1】:

    朋友声明不“继承”模板参数,但需要自己的:

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

    【讨论】:

    • 很抱歉,您能否详细说明一下。我不能完全掌握。
    • @Hummingbird 现在更清晰了吗?
    • @Hummingbird THX 进行编辑。在这种情况下,我永远不确定在哪里放置 friend 关键字。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-19
    • 2011-07-15
    • 1970-01-01
    相关资源
    最近更新 更多