首页 > 解决方案 > 编译器无法识别构造函数

问题描述

我正在尝试制作一个模板类,但由于某种原因,构造函数没有被识别。当我用 2 个值调用构造函数时,编译器会抛出一个错误,指出未定义的引用。我已经沮丧了一段时间,无法弄清楚出了什么问题。如果有人可以帮助我,将不胜感激这是代码:

对.h

#ifndef PAIR_H_INCLUDED
#define PAIR_H_INCLUDED
#include <iostream>
using size_t = decltype(sizeof 1);

namespace sdds
{
    template<typename K, typename V>
    class Pair
    {
    private:
        K k;
        V v;
    public:

        Pair(const K& key, const V& value);
        Pair() {}
        Pair(const Pair<K, V>& p);
        Pair<K, V> operator=(const Pair<K, V>& pair);
        const V& value() const;
        const K& key() const;
        void display(std::ostream& os) const;
    };

    template<typename K, typename V>
    std::ostream& operator<<(std::ostream& os, const Pair<V, K>& pair);
}

#endif // PAIR_H_INCLUDED

对.cpp

#include "Pair.h"

namespace sdds
{
    template<typename K, typename V>
    Pair<K, V>::Pair(const K& key, const V& value) //not being recognized
    {
        k = key;
        v = value;
    }

    template<typename K, typename V>
    Pair<K, V>::Pair(const Pair<K, V>& p)
    {
       k = p.k;
       v = p.v;
    }

    template<typename K, typename V>
    Pair<K, V> Pair<K, V>::operator=(const Pair<K, V>& pair)
    {
        k = pair.k;
        v = pair.v;

        return *this;
    }

    template<typename K, typename V>
    const K& Pair<K, V>::key() const
    {
        return k;
    }

    template<typename K, typename V>
    const V& Pair<K, V>::value() const
    {
        return v;
    }

    template<typename K, typename V>
    void Pair<K, V>::display(std::ostream& os) const
    {
        os << k << " : " << v << "\n";
    }

    template<typename K, typename V>
    std::ostream& operator<<(std::ostream& os, const Pair<V, K>& pair)
    {
        pair.display();
        return os;
    }

}

主文件

#include "Pair.h"
int main(int argc, char* argv[])
{

    sdds::Pair<int, int> pair(56, 44); //thows error here

    return 0;
}

错误:

 undefined reference to `sdds::Pair<int, int>::Pair(int const&, int const&)'

标签: c++classtemplatesconstructorcompiler-errors

解决方案


推荐阅读