我只是对我的文件应该是什么样子感到困惑。我不确定语法以及如何读取数组。
最佳答案
I'm just confused as to what my Map.cpp file is supposed to look like.
- 首先,你不能把你的模板类实现写在 .cpp 文件。它应该全部在头文件中。阅读以下 获取更多信息。 Why can templates only be implemented in the header file?
- 其次,
Map
类中没有构造函数声明 它以std::string
作为参数。提供一个!template <typename Domain, typename Range> class Map { public: Map(const std::string& filename); // declare one constructor which takes std::string // ... other members };
第三,您的成员函数定义缺少模板 参数。
template <typename Domain, typename Range> // ---> this void Map<Domain, Range>::add(Domain d, Range r) { // implementation } template <typename Domain, typename Range> // ---> this bool Map<Domain, Range>::lookup(Domain d, Range& r) { // implementation }
- 最后但并非最不重要的一点是,您缺少一个合适的析构函数,它是
Map
类必不可少,作为分配的内存(使用new
) 应该被释放。因此,相应地执行 The rule of three/five/zero .
也就是说,如果您可以使用 std::vector
,可以避免手动内存管理。
#include <vector>
template <typename Domain, typename Range>
class Map
{
public:
//...
private:
// other members
std::vector<Domain> dArray;
std::vector<Range> rArray;
};
作为旁注,避免使用 using namespace std;
进行练习。
Why is "using namespace std;" considered bad practice?
关于c++ - map 模板类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57985175/