c++ - 具有友元函数的模板类的链接器错误

标签 c++ visual-studio-2012 c++11 friend

我正在尝试用 forward_list 重新创建一个堆栈。但是,我使用友元函数来重载 + 和 << 运算符。

#pragma once
#include <forward_list>
template <class T> class Stack;

template <class T>
Stack<T> operator+(const Stack<T> &a, const Stack<T> &b){
//implementation
}

template <class T>
std::ostream &operator<<(std::ostream &output, Stack<T> &s)
{
//implementation
}

template <class T>
class Stack
{
friend Stack<T> operator+(const Stack<T> &a, const Stack<T> &b);
friend std::ostream &operator<<(std::ostream &output, Stack<T> &s);
std::forward_list<T> l;
public:
//Some public functions
};

对于这两个友元函数,当我尝试在我的 main 中调用它们时,我得到一个链接器错误:

int main(){
  Stack<int> st;
  st.push(4);
  Stack<int> st2;
  st2.push(8);
  cout<<st + st2<<endl;
  return 0;
}

这些是错误:

 error LNK2019: unresolved external symbol "class Stack<int> __cdecl operator+(class Stack<int> const &,class Stack<int> const &)" (??H@YA?AV?$Stack@H@@ABV0@0@Z) referenced in function _main
 error LNK2019: unresolved external symbol "class std::basic_ostream<char,struct std::char_traits<char> > & __cdecl operator<<(class std::basic_ostream<char,struct std::char_traits<char> > &,class Stack<int> &)" (??6@YAAAV?$basic_ostream@DU?$char_traits@D@std@@@std@@AAV01@AAV?$Stack@H@@@Z) referenced in function _main

提前致谢。

最佳答案

您在 Stack 类中的模板友元声明不太正确。您需要这样声明:

template<class T>
friend Stack<T> operator+(const Stack<T> &a, const Stack<T> &b);

template<class T>
friend std::ostream &operator<<(std::ostream &output, Stack<T> &s);

由于您使用的是MSVC,请see this Microsoft 文档以供进一步引用。

关于c++ - 具有友元函数的模板类的链接器错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26502594/

相关文章:

c++ - 自动扣除失败并显示消息 "inconsistent deduction for auto return type"

c++ - 如何防止在非常量对象上意外调用变异函数?

c++ - 编译器找不到我的标题?

c# - Package.Appxmanifest - 有什么方法可以在代码中获取此部分吗?

c++ - CL.exe 在 Visual Studio 2012 中崩溃

c++ - 为什么这个 lambda 可以流式传输?

c++ - 从源构建 mongodb 时出错

c++ - Visual C++ 断言在返回位置中断

c++ - 存在重载 C++ 运算符的问题

c++ - 自动存储和异常中没有无参数构造函数的类的对象