C++类模板复制构造器返回类型

C++ class template copy contructor return type

本文关键字:构造器 返回类型 复制 C++      更新时间:2023-10-16

我这样声明operator=

HashTable& operator=(const HashTable& aTable);

我在类外以以下方式定义它:

template <typename HashElement>
HashTable& HashTable<HashElement>::operator=(const HashTable& aTable)
{
    /*Do the copy thing*/
    return *this;
}

我希望它使用以下代码进行编译:

HashTable<EngWord> hashTable;
HashTable<EngWord> hashTableA;
hashTableA = hashTable;

但是编译器不喜欢定义的签名。错误消息是:

HashTable: suer of class template requires template argument list
HashTable<HashElement>::operation=': unable to match function definition or an existing declaration

根据我在互联网上看到的内容,它应该是我写作的方式。怎么了?

您必须将模板参数列表添加到返回类型中,如错误消息所示:

HashTable<HashElement>& HashTable<HashElement>::operator=(const HashTable& aTable)
参数

不需要模板参数列表,因为编译器已经知道您正在定义HashTable<HashElement>::operator=,您可以在其中使用注入的类名。

同样适用于在类模板定义中声明operator=。您可以在此处省略返回类型模板参数,但在类外部定义时则不能。