【问题标题】:template class operators "unresolved externals"模板类运算符“未解析的外部”
【发布时间】:2014-11-13 21:49:14
【问题描述】:

在我的课堂上:

#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 operator+(class MyVector,class MyVector)"

  2. Error 2 error LNK1120: 1 unresolved externals

已编辑:

添加了构造函数。

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

【问题讨论】:

  • 这可能是一个愚蠢的问题,但您是否包含了包含该类的头文件或者它是主源文件的一部分?
  • 我想你有 MyVector 的复制构造函数?
  • 另外,您应该使用const MyVector&lt;Type&gt;&amp; lhs, 作为左侧值。
  • 我包含了标题类。是的,我现在添加它。为什么我应该使用 const Im 复制对象并向其添加值。
  • 是的,我其他一切都很好。只有算术运算符没有。

标签: c++ class templates math class-template


【解决方案1】:

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

main.cpp:15:82: 警告:朋友声明 'MyVector operator+(MyVector, const MyVector&)' 声明一个 非模板函数 [-Wnon-template-friend] 朋友 MyVector operator+(MyVector lhs, const MyVector &rhs); //没有

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

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

还有it will build

friend 函数本身就是一个模板,其模板参数与 class MyVector 的模板参数不同。


更新:虽然上述方法似乎确实有效,但在阅读 this questionthis one 之后,我想知道这是否更正确:

// 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);
 };

【讨论】:

  • "// forward-declare class MyVector "这样我就可以在includes中定义我的方法了吗?
  • @Cirvis 前向声明需要解决循环依赖。这里MyVector需要知道operator+()operator+()需要知道MyVectortemplate&lt;class Type&gt; class MyVector; 通知编译器有一个名为 MyVector 的单参数类模板。这允许它在读取 operator+() 的声明时理解名称 MyVector
  • 如果是这样,为什么编译器不会抛出任何错误?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-06-19
  • 1970-01-01
  • 2011-10-21
  • 2011-08-12
  • 1970-01-01
  • 1970-01-01
  • 2014-04-03
相关资源
最近更新 更多