【问题标题】:Map template class地图模板类
【发布时间】:2019-09-18 04:38:15
【问题描述】:

我只是对我的文件应该是什么样子感到困惑。我不确定语法以及如何读取数组。

【问题讨论】:

  • 你已经把你之前在第一个问题中的代码编辑掉了。我建议把它带回来。另外,如果以下答案有帮助,请告诉我。

标签: c++ class templates syntax member-functions


【解决方案1】:

我只是对我的 Map.cpp 文件应该是什么样子感到困惑。

  • 首先,你不能把你的模板类实现写在 .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?

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-03-18
  • 1970-01-01
  • 1970-01-01
  • 2017-10-06
  • 1970-01-01
  • 2022-11-12
  • 2014-02-13
相关资源
最近更新 更多