类模板C++错误

Class Template C++ Errors

本文关键字:错误 C++      更新时间:2023-10-16

更新了文件,但我仍然收到以下错误。

  • 1未解析的外部(lab12.exe第1行)
  • 未解析的外部符号"public char__thiscall Pair::geetFirst(void)"(?getFirst@$Pair@D@@QAEDXZ)(lab12.obj第1行)

配对h

#pragma once
template <class T>
class Pair
{
private:
    T theFirst;
    T theSecond;
public:
    /*Pair(const T& dataOne, const T& dataTwo);*/
    Pair(T a, T b) {
        theFirst = a;
        theSecond = b;
    }
    T getFirst();
    T getSecond();
};

配对.cpp

#include "stdafx.h"
#include "Pair.h"

template<class T>
T Pair<T>::getFirst()
{
    return theFirst;
}
template<class T>
T Pair<T>::getSecond()
{
    return theSecond;
}

Main.cpp

#include "stdafx.h"
#include "Pair.h"
#include <iostream>
using namespace std;
int main()
{
    Pair <char> letters('a', 'd');
    cout << letters.getFirst();

    cout << endl;
    system("Pause");
    return 0;
}

你已经被using namespace std;咬了一口。您有自己的pair类,但在标准库中有一个std::pair。编译器无法决定使用哪一个,因此会出现不明确的符号错误。

解决方案:不要使用using namespace std;!用std::限定标准库符号。这样可以省去很多头疼的事。

命名空间std还包含一个名为pair的模板类。

您需要将自己的对模板包装在自己的命名空间中,或者将其命名为其他名称,这样您就可以调用它而不会出现不明确的符号错误。