Function 如何从另一个cpp文件中的函数返回结构(在.h文件中定义)?
我遇到了这个问题,我无法处理它。如有任何建议,我们将不胜感激。 我在头文件中定义了如下结构: 结果:hFunction 如何从另一个cpp文件中的函数返回结构(在.h文件中定义)?,function,structure,Function,Structure,我遇到了这个问题,我无法处理它。如有任何建议,我们将不胜感激。 我在头文件中定义了如下结构: 结果:h #ifndef RESULTS_H #define RESULTS_H struct Results { double dOptSizeMWh; double dOrigSOCFinal; double dManiSOCFinal; }; #endif 以及Deterministic中“Deterministic”函数的一般定义。h: #ifndef DETERM
#ifndef RESULTS_H
#define RESULTS_H
struct Results
{
double dOptSizeMWh;
double dOrigSOCFinal;
double dManiSOCFinal;
};
#endif
以及Deterministic中“Deterministic”函数的一般定义。h:
#ifndef DETERMINISTIC_H
#define DETERMINISTIC_H
Results Deterministic(int,int,int,double,double); //Deterministic(int nNoMonth, int nNOWind, int nWindLength, double dPreviousSizeMWh, double dPreviousSOC)
#endif;
此函数在Deterministic.cpp中实现:
#include "Results.h"
Results Deterministic(int nNoMonth, int nNOWind, int nWindLength, double dPreviousSizeMWh, double dPreviousSOC)
{
// returns number of rows and columns of the array created
struct Results sRes;
sRes.dOptSizeMWh = -1.0; // for the optimal size of battery in MWh
sRes.dOrigSOCFinal = -1.0; // for the SOC at the end of the window
sRes.dManiSOCFinal = -1.0; // this is set to 0.0 if final SOC is slightly below 0
//...........................////
// OTHER Calculation .......////
//...........................////
return sRes;
}
最后,我有一个主文件,我称之为Deterministic function,并使用结果结构main.cpp:
#include <Results.h>
#include <Deterministic.h>
using namespace std;
int main ()
{
int nNoMonth = 1; // the month that we want to use in the input
int nWindLength = 1; // length of window, hour
int nNODays = 1; // number of days that we want to repeat optimization
struct Results dValues;
double **mRes = new double*[nNODays * 24 / nWindLength];
for (int i = 0; i < nNODays * 24 / nWindLength; ++i) mRes[i] = new double[3];
for (int i = 0; i < nNODays * 24 / nWindLength; i++)
{
if (i == 0)
{
dValues = Deterministic(nNoMonth, i, nWindLength, 0.0, 0.0);
}else
{
temp0 = *(*(mRes+i-1)); double temp1 = *(*(mRes+i-1)+1); double temp2 = *(*(mRes+i-1)+2);
if (temp2 == -1.0) {dValues = Deterministic(nNoMonth, i, nWindLength, temp0, temp1);}
else {dValues = Deterministic(nNoMonth, i, nWindLength, *(*(mRes+i-1)), *(*(mRes+i-1)));}
}
*(*(mRes+i)) = dValues.dOptSizeMWh;
*(*(mRes+i)+1) = dValues.dOrigSOCFinal;
*(*(mRes+i)+2) = dValues.dManiSOCFinal;
}
#包括
#包括
使用名称空间std;
int main()
{
int nNoMonth=1;//要在输入中使用的月份
int nWindLength=1;//窗口长度,小时
int nNODays=1;//要重复优化的天数
结构结果值;
双精度**mRes=新双精度*[nNODays*24/nWindLength];
对于(int i=0;i
这些只是Deterministic.cpp和main.cpp中定义问题的代码的一小部分。第一个循环进行得很好(即i=0),没有任何问题,但在第二个循环中失败,并出现以下错误:“R6010-abort()已被调用”
这个错误出现在main.cpp中,我在if语句中调用Deterministic函数。我编译和运行发布的代码没有问题(除了
temp
声明前面缺少的double
),而不知道什么是Deterministic()
实际上正在做,很难猜测问题是什么(除以零?播放Justin Bieber mp3?)。这与从另一个文件中定义的函数返回结构无关(翻译单元是语言的基本功能)。要找到根本原因,只需一步(完成)Deterministic()
使用调试器。使用调试器调查崩溃。Andrew,谢谢你的回答。我尝试过,但它没有明确说明根本原因,但当我立即调用Deterministic时,它失败了。它根本不检查Deterministic中的代码以便我能够调试它。好的,我找到了。我在如你所说,用确定性代码编写。感谢你的帮助。