加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 模板类的友元函数中的链接错误

发布时间:2020-12-16 07:18:00 所属栏目:百科 来源:网络整理
导读:我有模板类节点,为了遵循 copy-and-swap惯用法,我尝试编写交换函数,这是类Node的朋友 我的代码是: Node.h #ifndef NODE_H#define NODE_H#includememorytemplatetypename typeclass Node{ type data_; std::unique_ptrNode next_;public: Node(type data); N
我有模板类节点,为了遵循 copy-and-swap惯用法,我尝试编写交换函数,这是类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> &)

解决方法

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读