DynamicMassives.h
//------------------------------------------------------------- create simple massive
template <typename T>
T * getArray(int &len) { // returns pointer to dynamic massive
T *ptr;
if (!(ptr = new T[len])) { // conditional of possibility of memory allocation
cout << "can't allocate memory..." << endl;
return nullptr; // protection if there is no memory rest
}
else return ptr;
}
源码.cpp
#include <iostream>
#include <ctime> // for random
#include "DynamicMassives.h"
using namespace std;
int main(void) {
srand(time(NULL)); // randomize
//----------------------------------------------- Simple dynamic massive
cout << "simple dynamic massive:" << endl;
int *parr; // pointer for dynamic massive
int len = 20; // length of dynamic massive
parr = getArray(len); // call for dynamic massive creating function <<<<<<<<<<<<< ERROR!!!!
cout << endl;
system("pause");
}
结论:
错误 C2672“getArray”:未找到匹配的重载函数
错误 C2783 T *getArray(int &):无法为“T”编写模板参数
你能告诉我模板有什么问题吗?如果没有带有 int 的模板,它在任何地方都能完美运行。
您需要显式指定存储在数组中的元素的类型:
更远:
运算符
new
的行为与函数的行为不同malloc
——如果由于某种原因无法分配内存——将引发异常。因此,在 C 中您可以使用类似的构造,但在 C++ 中您不能:从参数推断类型的函数示例:
在您的示例中的 f-ii 中,无法自动推断出类型 - 因为 作为参数,您使用一个数字来表征数组中元素的数量,而不是这些元素的类型。