模板类运算符"unresolved externals"

template class operators "unresolved externals"

本文关键字:unresolved externals 运算符      更新时间:2023-10-16

在我的类中:

#ifndef __MYVECTOR_CLASS__
#define __MYVECTOR_CLASS__
template<class Type>
class MyVector{
    ....
    MyVector& operator=(const MyVector& source); //works
    friend MyVector<Type> operator+(MyVector<Type> lhs, const MyVector<Type> &rhs); //doesnt
    ....
};
template<class Type>
MyVector<Type>& MyVector<Type>::operator=(const MyVector &v){
    if (_d != v._d){
        _d = v._d;
        _deleteArray();
        _createArray(_d);
    }
    _assignValues(v._vector, (v._vector + _d));
    return *this;
};

template<class Type>
MyVector<Type> operator+(MyVector<Type> lhs, const MyVector<Type> &rhs){
    if (lhs._d == rhs._d){
        for (int index = 0; index < lhs._d; index++){
            lhs._vector[index] += rhs._vector[index];
        }
    }
    return lhs;
};
#endif // __MYVECTOR_CLASS__

不包括其他非操作员功能,因为它们都可以正常工作。不知道为什么它不起作用。

在源文件中:

int main(){
    MyVector<float> a(10);

    MyVector<float> b(10);
    a = b; // works alone
    a = a + b; //breaks
    return 0;
}

和错误:

    错误
  1. 1 错误 LNK2001:未解析的外部符号"类"MyVector __cdecl 运算符+(class MyVector,class我的矢量)"

  2. 错误
  3. 2 错误 LNK1120:1 个未解析的外部

已编辑:

添加了构造函数。

template<class Type>
MyVector<Type>::MyVector(int size){
    _d = size;
    _createArray(_d);
    _assignValues(0);
}

如果您尝试使用 coliru 进行编译,您将收到以下警告:

主.cpp:15:82: 警告:好友声明"我的矢量" operator+(MyVector, const MyVector&)' 声明 非模板函数 [-Wnon-模板友元] friend MyVector operator+(MyVector lhs, const MyVector &rhs);不

这应该可以作为正在发生的事情的线索。将代码更改为:

template<typename T>
friend MyVector<T> operator+(MyVector<T> lhs, const MyVector<T> &rhs);

它会建立。

friend 函数本身是一个模板,其模板参数与 class MyVector 的参数分开。


更新:虽然上述似乎确实有效,但在阅读了这个问题和这个问题之后,我想知道这是否更正确:

// forward-declare class MyVector
template<class Type>
class MyVector;
// forward-declare operator+()
template<class Type>
MyVector<Type> operator+(MyVector<Type> lhs, const MyVector<Type> &rhs);
template<class Type>
class MyVector{
    // declare that the already-declared operator+<>() is a friend
    friend MyVector<Type> operator+<>(MyVector<Type> lhs, const MyVector<Type> &rhs);
 };