在尝试使用样本输入运行 Pairwise 类后,我得到了一个 undefined reference 。我的 Pairwise 类是在头文件中创建的,我创建了一个主要函数来将键和值作为字符串传递,以便按照我的意愿对它们进行格式化。
我的预期输出:
key:value
我的头文件:
#pragma once
#include<iostream>
using std::ostream; using std::cout; using std::endl;
#include<string>
using std::string;
#include<sstream>
using std::ostringstream;
template<typename K, typename V>
struct Pairwise {
K first;
V second;
Pairwise() = default;
Pairwise(K,V);
friend ostream& operator<<(ostream &out, const Pairwise &p){
out << p.first << ":" << p.second;
return out;
}
};
我的主要功能:
#include "file.h"
#include<iostream>
using std::cout; using std::endl;
#include<sstream>
using std::ostringstream;
#include<string>
using std::string;
int main()
{
Pairwise<string,string> p("key", "value");
ostringstream oss;
oss<<p;
string example = oss.str();
cout << example << endl;
}
我得到的错误:
/tmp/ccfv4iaY.o: In function `main':
main_program.cpp:(.text+0x8b): undefined reference to `Pairwise<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > >::Pairwise(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >)'
collect2: error: ld returned 1 exit status
最佳答案
您的模板包含 Pairwise(K,V);
的声明,但它从未在任何地方定义/实现。
您需要在同一个(或另一个)头文件中添加定义。要验证,将 ;
替换为 {}
,链接器错误应该消失:Pairwise(K,V) {}
(它赢了' 工作,但它会编译和链接正常)。
关于c++ - 对模板类成员的 undefined reference ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53464403/