关于C ++中的动态数组构造

时间:2012-03-27 02:17:20

标签: c++ templates dynamic-memory-allocation

我正在修改机器学习项目的C ++技能。所以,我正在研究动态分配内存功能。我的想法是将这些函数定义为静态函数,并将它们放在一个类中,然后根据需要调用它们。所以我定义了以下名为Utils.h的头文件 -

//Utils.h
#include <stdio.h>

class Utils
{
public:
    template<class T> static T* create1DArray(int size);            
};

然后我创建了以下Utils.cpp作为 -

//Utils.cpp
#include<stdio.h>
#include<malloc.h>
#include"Utils.h"


template<class T> T* Utils::create1DArray(int size)
{
    T* a = new T [size];
    return a;
}

然后我测试了它们 -

#include<iostream>
#include<conio.h>
#include"Utils.cpp"

using namespace std;
int main()
{
    cout<<"Test";
    double* a;    
    int n=3;
    a = Utils.create1DArray<double>(n);
    getch();
    return 0;   
}

但是我遇到了以下错误 -

error C2275: 'Utils' : illegal use of this type as an expression    
error C2228: left of '.create1DArray' must have class/struct/union  
error C2062: type 'double' unexpected   

但令人惊讶的是,当我将这个功能作为一个独立的功能而没有放入它所使用的功能时。知道怎么解决吗?

1 个答案:

答案 0 :(得分:2)

您正尝试使用.点表示法来调用静态方法。

改为使用::正确的运算符。

Utils::create1DArray<double>(n)
相关问题