首页 > 解决方案 > 如何解决 .cpp 和 .hpp 文件中的 calloc() 错误?

问题描述

我尝试使用这个命令在 Linux中运行.cpp一个文件:但我有这个错误:.hppg++ -c main.cppcalloc()

错误:“calloc”没有依赖于模板参数的参数,因此“calloc”的声明必须可用[-fpermissive]
   Tr=(T *)calloc(行*列, sizeof(T));

在成员函数 'T* MyMatrix::Adjoint()' 中:
MyMatrix.hpp:276:35: 错误: 'calloc' 没有依赖于模板参数的参数,因此'calloc' 的声明必须可用 [-fpermissive]
   温度 = (T*)calloc(N*N, sizeof(T));

我注意到这段代码在 Microsoft Visual Studio 中工作:

#pragma once
#include <iostream>
#include <fstream>

template <typename T>
class MyMatrix {
private:
    int Rows;
    int Colomns;
    T* A; //Matricea
    T* Tr; //Transpusa acesteia
    float* Inv; //Inversa
public:
    MyMatrix(int L, int C)
    {

        Rows = L;
        Colomns = C;

        A = (T*)calloc(Rows * Colomns, sizeof(T));
        if (A == NULL)
            throw("Eroare la alocarea matricii! :(");
    }

    MyMatrix(T* S, int L, int C)
        : MyMatrix(L, C)
    {
        for (int i = 0; i < Rows * Colomns; ++i)
            A[i] = S[i];
    }

    ~MyMatrix() { free(A); }

    void Transposed()
    {
        Tr = (T*)calloc(Rows * Colomns, sizeof(T));
        for (int i = 0; i < Colomns; ++i)
            for (int j = 0; j < Rows; ++j)
                Tr[j * Colomns + i] = A[i * Rows + j];
    }

    void Inverse()
    { //some code
        T* Adj = Adjoint();
        Inv = (float*)calloc(Rows * Rows, sizeof(float));
        for (int i = 0; i < this->Rows * this->Rows; ++i)
            Inv[i] = Adj[i] / (float)Det;
    }
};

#endif // MYMATRIX_HPP_INCLUDED

标签: c++templatesunixg++calloc

解决方案


'calloc' 声明必须可用

解决方案是在使用前声明calloc。由于它是标准函数,因此必须通过包含指定声明它的标准头来声明它。

calloc在标题中声明<stdlib.h>。请注意,.h不推荐使用 C 标准库中的带后缀的头文件,而赞成使用带c前缀的头文件,例如<cstdlib>. 但是,c前缀标头声明了std您在这种情况下未能使用的命名空间中的函数。

所以完整的解决方案是包含<cstdlib>并使用std::calloc.


但是,您根本不需要使用calloc。更好的解决方案是使用std::make_uniqueor std::vector


推荐阅读