【发布时间】:2018-03-30 06:27:28
【问题描述】:
我在用 C++ 实例化模板类类型的对象时遇到问题。
代码如下:
数组.h:
//Developed by Trofimov Yaroslav on 30.03.2018
#ifndef _ARRAY_H_TROFIMOV_
#define _ARRAY_H_TROFIMOV_
template<size_t n, typename T>
class Array
{
static unsigned __freeId, __quantity;
unsigned _id;
T* _array;
public:
template<size_t n, typename T>
Array(void);
~Array(void);
T& operator[](const size_t);
};
#include "Array.cpp"
#endif
数组.cpp:
//Developed by Trofimov Yaroslav on 30.03.2018
#include "Array.h"
template<size_t n, typename T>
Array::Array(void)
: _id(++__freeId), _array(new T[]) {
}
template<size_t n, typename T>
Array::~Array(void) {
}
template<size_t n, typename T>
T& Array::operator[](const size_t i) {
}
Main.cpp:
//Developed by Trofimov Yaroslav on 30.03.2018
#include <iostream>
#include "Array.h"
int main(void) {
Array<7, int> a;
return 0;
}
现在,当我将鼠标悬停在 Main.cpp 中的 a 上时,我看到以下内容:
错误:类“Array”不存在默认构造函数
但正如您所见,默认模板构造函数确实存在。那么,我在这里缺少什么?
【问题讨论】:
-
template<size_t n, typename T> Array(void);-->Array();stackoverflow.com/questions/495021/… -
@liliscent,谢谢。我以前读过这篇文章,但我仍然无法在这里解决我的问题。
-
@ggghahaha 就像 liliscent 说的,你需要从构造函数中删除额外的
template,它不属于那里。此外,在您的 cpp 文件中,您需要将所有Array::替换为Array<n, T>:: -
@RemyLebeau,在替换了第一个
Array::并删除了template之后,我得到了错误语法错误。因此,我认为你的建议没有用。
标签: c++ templates constructor