【问题标题】:Template (C++) - not sure if correct模板 (C++) - 不确定是否正确
【发布时间】:2012-05-25 18:20:58
【问题描述】:

我是一名学生,我正在为 C++ 中的数组做一个静态库,所以我不必每次上课都重写代码。

我在中学二年级,所以我不是专家。 我希望我的代码与所有类型(int、float、ecc)兼容,但我遇到了一些麻烦。

你能看看我的代码吗?

// slarray.h
#if !defined _SLARRAY_
#define _SLARRAY_

template <typename Tipo> class Array {
  public:
    void inserisci();
    void visualizza();
    void copia(Tipo*);
    Array(short);
    ~Array();
  private:
    Tipo* ary;
    short* siz;
};

#endif

// slarray.cpp   
#include <iostream>
#include "slarray.h"

unsigned short i;
unsigned short j;

template <typename Tipo> void Array<Tipo>::inserisci() {
  for (i = 0; i < *siz; i++) {
    std::cout << i << ": ";
    std::cin  >> ary[i];
  }
}
template <typename Tipo> void Array<Tipo>::visualizza() {
  for (i = 0; i < *siz; i++) {
    std::cout << ary[i] << " ";
  }
}
template <typename Tipo> void Array<Tipo>::copia(Tipo* arycpy) {
  for (i = 0; i < *siz; i++) {
    *(arycpy + i) = ary[i];
  }
}
template <typename Tipo> Array<Tipo>::Array(short n) {
  siz = new short;
  *siz = n;
  ary = new Tipo[n];
}
template <typename Tipo> Array<Tipo>::~Array() {
  delete[] ary;
  delete siz;
}

当我尝试初始化类时,代码给了我错误:

Array <int> vct(5);

【问题讨论】:

标签: c++ class templates


【解决方案1】:

模板实现需要对专门化它们的翻译单元可见。

将实现从cpp移动到头文件。

其他几点说明:

  • unsigned short i;unsigned short j; 应该是本地的,不需要将它们作为全局变量。

  • _开头后跟一个大写字母的宏是保留的,所以_SLARRAY_是非法的,重命名它。

  • 实现赋值运算符和复制构造函数,否则所有的复制都是浅的。

我假设你不能使用std,否则你知道容器已经存在那里,对吧?

【讨论】:

  • 现在可以了,非常感谢!但是,在头文件中编写实现是否不正确?我应该在.cpp文件中写什么?
  • @Edoardo 是的,这就是模板的工作方式。通常没有对应的cpp 文件,只有标题。
  • 这样,Visual Studio 不会构建 .lib 文件。
  • @Edoardo 即使没有,也不需要库。不需要导出符号,因为实现都是可见的。这就是模板的工作原理。
  • 找到了方法。我在 .cpp 文件的底部添加了我需要的实例化实现:模板数组 ;
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-08
  • 1970-01-01
  • 1970-01-01
  • 2021-09-12
  • 1970-01-01
  • 2017-02-11
相关资源
最近更新 更多