模板(C ++) - 不确定如果正确 [英] Template (C++) - not sure if correct

查看:144
本文介绍了模板(C ++) - 不确定如果正确的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一个学生,我正在使用C ++中的数组的静态库,所以我不必每次在课程中重写代码。

I'm a student and I'm doing a static library for arrays in C++, so I don't have to rewrite code every time during lessons.

我在中学的第二年,所以我不是一个专家。
我想让我的代码与所有类型(int,float,ecc。)兼容,但我有一些麻烦。

I'm at second year in a secondary school so I'm not an expert. I want my code to be compatible with all type (int, float, ecc.) but I'm having some trouble.

在我的代码?

// 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;
}

当我尝试使用初始化类时, p>

The code gives me errors when I try to inizialize the class with:

Array <int> vct(5);


推荐答案

模板实现需要对专业翻译单元

Template implementations need to be visible to translation units that specialize them.

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

Move the implementations to the header file from the cpp.

其他几个注释:


  • 无符号short i;

  • unsigned short i;unsigned short j; should be made local, there's no need to have them as global variables.

开头的宏

Macros starting with _ followed by a capital letter are reserved, so _SLARRAY_ is illegal, rename it.

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

Implement an assignment operator and copy constructor, otherwise all copying will be shallow.

你不能使用 std ,否则你知道容器已经存在了,对吗?

I'm assuming you can't use std, otherwise you are aware that containers already exist there, right?

这篇关于模板(C ++) - 不确定如果正确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆