【问题标题】:How can I resolve calloc() error in .cpp and .hpp files?如何解决 .cpp 和 .hpp 文件中的 calloc() 错误?
【发布时间】:2019-06-18 13:50:58
【问题描述】:

我尝试使用以下命令在 Linux 中运行带有.hpp 文件的.cppg++ -c main.cpp,但我有这个关于calloc() 的错误:

错误:“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

【问题讨论】:

  • 最好的解决办法是根本不使用calloc。请改用std::vector
  • 如果您迫切需要手动管理内存,您应该使用 new[]delete[],而不是 C 函数。
  • 查找在哪个标头calloc 中声明了。
  • 停止用 C++ 编写 C!只需使用std::vector 并应用“零规则”。

标签: c++ templates unix g++ calloc


【解决方案1】:

“calloc”声明必须可用

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

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

所以完整的解决方案是包含&lt;cstdlib&gt;,并使用std::calloc


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

【讨论】:

    【解决方案2】:

    正如错误消息所暗示的,这里使用的 g++ 编译器没有第二个参数是模板类型的实现,即当第二个参数是 int 或 float 类型时,编译器会识别参数,因为这些是编译器的类型知道它的“calloc”实现适用于这些类型,但它无法识别第二个参数何时是模板类型。 此处使用的 Visual Studio 可能具有允许将模板类型传递给“calloc”的实现。 也许您可以尝试将 g++ 编译器更新到最新版本,然后它可能会支持您在此处尝试执行的操作。

    希望这会有所帮助!

    【讨论】:

    • 不,T 不是“模板类型”,问题与传递给calloc 的类型无关。问题只是没有包含声明calloc 的适当标头。
    猜你喜欢
    • 2021-04-15
    • 1970-01-01
    • 2021-04-25
    • 2019-11-12
    • 2016-11-15
    • 1970-01-01
    • 2016-12-21
    • 1970-01-01
    • 2021-09-15
    相关资源
    最近更新 更多