gpt4 book ai didi

C++如何定义嵌套类中的运算符

转载 作者:行者123 更新时间:2023-11-27 22:41:18 25 4
gpt4 key购买 nike

我在定义嵌套类中的运算符时遇到了问题,该嵌套类也是模板化的。我了解如何在 .h 文件中声明和定义它,但我想在 .h 文件中声明它并在 .hpp 文件中定义它。例如:

列表.h

template <typename T>
class List {
public:
class const_iterator { //nested class
//....
const T & operator*() const;
};
};

下面是我不太明白的部分:

列表.hpp

#include "List.h"
template <typename T>
typename List <T>::const_iterator & List <T>:: operator*() const //error line
{
//do stuff
}

我在 Line.hpp 的第 4 行收到的错误是:

Out-of-line definition of 'operator*' does not match any declaration in 'List<T>'

我正在寻找一种只涉及修复 .hpp 文件的解决方案。

最佳答案

如错误所述,您的定义与您的声明不匹配。您已声明成员 operator*类(class) List<T>::const_iterator返回 const T& ,但您的定义是针对成员 operator*类(class) List<T>返回 List<T>::const_iterator& .

类模板的成员函数的定义,无论是否嵌套,都遵循与任何其他函数相同的模式:ReturnType FunctionName(ParameterList)

该声明的适当定义是:

  template <typename T>
const T& List<T>::const_iterator::operator*( ) const
//^^^^^^^^ ^
// | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
// Return type | (empty) parameter list
// Function name
{
//...
}

关于C++如何定义嵌套类中的运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48759148/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com