c++ - 如何解决 .cpp 和 .hpp 文件中的 calloc() 错误?
问题描述
我尝试使用这个命令在 Linux中运行.cpp
一个文件:但我有这个错误:.hpp
g++ -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' 声明必须可用
解决方案是在使用前声明calloc
。由于它是标准函数,因此必须通过包含指定声明它的标准头来声明它。
calloc
在标题中声明<stdlib.h>
。请注意,.h
不推荐使用 C 标准库中的带后缀的头文件,而赞成使用带c
前缀的头文件,例如<cstdlib>
. 但是,c
前缀标头声明了std
您在这种情况下未能使用的命名空间中的函数。
所以完整的解决方案是包含<cstdlib>
并使用std::calloc
.
但是,您根本不需要使用calloc
。更好的解决方案是使用std::make_unique
or std::vector
。
推荐阅读
- javascript - 网址在 gMail 中被强制重定向
- r - ggplot 使用 facet_wrap 在 x 轴上等量刻度
- orientdb - 使用 OrientDB studio 查询 OrientDB 时出现 BufferUnderflowException
- mysql - 如何在同一个选择查询中将一个表的值交换到另一个表的值?
- java - Mediaplayer 操作按钮下一个、上一个、重复和随机播放
- wpf - 从材料设计中设计激活指示器
- plugins - TFS 2018 签入策略插件问题,从 TFS Web 界面签入时发现 notificationEventArgs.NotificationInfo.WorkItemInfo 为 null
- python - 使用python导出csv后错误的单元格
- python - 获取数据帧行,其中每个 T 列序列有 1 N 次
- javascript - javascript,按索引合并两个数组