【问题标题】:undefined reference to all friend functions对所有友元函数的未定义引用
【发布时间】:2016-09-11 17:56:00
【问题描述】:

我的 Set 类中有两个模板化的重载友元函数,它们不断发回错误

Templatedriver.cpp:(.text+0x2a0): undefined reference to `std::ostream& operator<< <int>(std::ostream&, Set<int> const&)'

Templatedriver.cpp:(.text+0x2dd): undefined reference to `std::ostream& operator<< <int>(std::ostream&, Set<int> const&)'

等等(只需将输出更改为 double、char 等) 我已经对此进行了搜索,这里最常见的响应是进行前向声明,然后将其声明为班级中的朋友,我已经这样做了,但仍然得到一个未定义的引用

这是我的前瞻声明

template <class T> istream& operator>>(istream&, Set<T>&);
template <class T> ostream& operator<<(ostream&, const Set<T>&);

我在类中声明它们

template <class T>
class Set {

friend istream& operator>> <>(istream&, Set<T>&); 
template <class Y> */friend ostream& operator<< <>(ostream&, const Set<T>&);
....//rest of class
}

这些是定义

template <class T> istream& operator>>(istream& is, Set<T>& S){
    S.input();
    return(is);
}


template <class T> ostream& operator<<(ostream& os, const Set<T>& S){
        S.display();
        return(os);   
}

还有一些重载的类我遇到了麻烦,但都是同样的问题

【问题讨论】:

  • 头文件中有定义吗?
  • immibis 的问题很重要。如果您的Set&lt;int&gt; 实例化看不到operator&lt;&lt;operator&gt;&gt; 实现,那么它们永远不会被实例化。
  • 不,定义在Set.cpp中,那么它们应该在头文件中吗?
  • 如果模板函数仅在该文件中使用,则它们应仅在实现文件 (cpp) 中定义。否则,它们需要在标题中。这是因为使用类型 X 的文件需要模板定义来实例化适用于类型 X 的实例。
  • 你的问题。定义必须在头文件中。这是stackoverflow.com/questions/495021/…的骗子

标签: c++ templates overloading friend


【解决方案1】:

Set,我想你想使用一个模板化的朋友声明:

template <typename T>
friend istream& operator>> (istream&, Set<T>&);

这声明任何在模板参数替换后匹配的函数都是该类的友元。

(您可能几乎遇到过这个问题,但我被代码中的*/ 弄糊涂了。只要说您应该删除&lt;&gt;。)

【讨论】:

  • 啊该死的我是想在这里删除它,*/之前的东西不应该在那里,我曾经这样做过,但没有用
猜你喜欢
  • 2021-09-24
  • 1970-01-01
  • 2015-06-06
  • 2021-08-05
  • 2019-09-05
  • 2011-09-19
  • 2017-10-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多