c++ - map 模板类

标签 c++ class templates syntax member-functions

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

最佳答案

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/

相关文章:

c++ - C++平台游戏中的寻路

c++ - C++ 中的闭包

c++ - c++ 内联显式构造函数有什么用?

PHP 在类中打印错误

Python函数调用

c++ - 虚拟关键字内部结构

java - Android帮助,试图将值(value)从一个类转移到另一个类(android应用程序)

来自不同类的 C++ 多个回调成员函数,没有 std 和 boost

angular - Angular 组件的自定义 CSS 属性

c++ - 针对非类型参数特定值的模板代码优化。