Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 链接器错误:模板关系运算符_C++_Templates - Fatal编程技术网

C++ 链接器错误:模板关系运算符

C++ 链接器错误:模板关系运算符,c++,templates,C++,Templates,为什么这段代码会给我一个链接器错误,我该如何修复它 架构x86\u 64的未定义符号:“运算符==(foo const&,foo const&)”,引用自:\u main in main.o ld:未找到架构x86\u 64的符号 template<typename T> class foo { //friends get access to the private member t friend bool operator==(const foo<T> &

为什么这段代码会给我一个链接器错误,我该如何修复它

架构x86\u 64的未定义符号:“运算符==(foo const&,foo const&)”,引用自:\u main in main.o ld:未找到架构x86\u 64的符号

template<typename T>
class foo {
  //friends get access to the private member t
  friend bool operator==(const foo<T> &lhs, const foo<T> &rhs);
  T t;
};

template<typename T>
bool operator==(const foo<T> &lhs, const foo<T> &rhs) {
  return lhs.t == rhs.t;
}

int main(int,char**) {
  foo<int> f1, f2;
  if (f1 == f2)
    ;
  return 0;
}
模板
福班{
//朋友可以访问私人会员t
友元布尔运算符==(常量foo和lhs,常量foo和rhs);
T;
};
模板
布尔运算符==(常数foo和lhs、常数foo和rhs){
返回lhs.t==rhs.t;
}
int main(int,char**){
foo-f1,f2;
如果(f1==f2)
;
返回0;
}

重载运算符时,避免使用友元函数;您需要将函数定义为公共类成员,并使其只接受一个参数(而不是两个)

模板
福班{
//允许访问私有成员t的公共函数
公众:
布尔运算符==(foo和rhs)
{
返回t==rhs.t;
}
私人:
T;
};
int main(int,char**){
foo-f1,f2;
如果(f1==f2)
;
返回0;
}

以下是您的代码修复程序:

template<typename T>
class foo; // Forward declaration

template<typename T> // Need to define or declare this before the class
bool operator==(const foo<T> &lhs, const foo<T> &rhs) {
  return lhs.t == rhs.t; 
}

template<typename T>
class foo {
  // Notice the little <> here denoting a specialization
  friend bool operator==<>(const foo<T> &lhs, const foo<T> &rhs);
  T t;
};
模板
类别foo;//远期申报
模板//需要在类之前定义或声明
布尔运算符==(常数foo和lhs、常数foo和rhs){
返回lhs.t==rhs.t;
}
模板
福班{
//注意这里表示专门化的一点
友元布尔运算符==(常量foo和lhs,常量foo和rhs);
T;
};

运算符==
是一个函数模板,但友谊声明没有反映这一点。这是修复它的一种方法:

template <class U>
friend bool operator==(const foo<U> &lhs, const foo<U> &rhs);
模板
友元布尔运算符==(常量foo和lhs,常量foo和rhs);

一个很小的问题是它给了
operator==
朋友访问
foo
的权限。出于这个原因,我认为@JesseGood的修复更干净,尽管(矛盾的是)更详细。

您需要再次指定模板类型,但与类模板类型不同:

template<typename V>
friend bool operator==(const foo<V> &lhs, const foo<V> &rhs);
模板
友元布尔运算符==(常量foo和lhs,常量foo和rhs);

不,一般来说,您不需要,因为这会导致左右侧的自动转换不对称。首先声明函数就足够了。@SebastianRedl:
foo
在类定义之前是未知的,您需要在类内或类后进行向前声明或定义。@JesseGood:我认为Sebastian的意思是,向前声明
运算符==
就足够了。由于它以任何一种方式编译,所以这是否必要还是一个悬而未决的问题+1,无论如何。回答得不错。我的意思是,您可以在类模板定义之前声明运算符==模板,然后在类模板定义之后定义运算符==模板。因为我更喜欢类定义出现在任何使用它的函数之前,所以我更喜欢这样做。我不是建议你可以省略类模板声明。@SebastianRedl:啊,我明白了。我将其编辑为
define或declare
。谢谢
template<typename V>
friend bool operator==(const foo<V> &lhs, const foo<V> &rhs);