我编写了一段使用复杂库的代码。我已将函数的定义放在头文件中,而在main.cpp中我已经定义了复数“I”,如下面的代码所示。 但是当我想编译这段代码时,我会收到错误。
我认为头文件中的函数不能使用复杂的库。 我该如何解决这个问题?
感谢。
的main.cpp
#include <iostream>
#include "math.h"
#include <complex>
#include "header.h"
using namespace std;
typedef complex<double> cmp;
cmp I(0.0,1.0);
int main()
{
cout << function(5.0) << endl;
return 0;
}
header.h
#ifndef header
#define header
double function(double x)
{
return 5*exp(I*x).real();
}
#endif
答案 0 :(得分:3)
问题是解析头文件时未定义I
。您需要在I
之前移动#include "header.h"
的定义。
答案 1 :(得分:3)
因为在I
包含之后定义了header
,所以main.cpp基本上就变成了这样:
double function(double x)
{
return 5*exp(I*x).real();
}
using namespace std;
typedef complex<double> cmp;
cmp I(0.0,1.0);
编译器解析你的函数,并抛出一个错误,因为它不知道{尚}是什么{。}}。
您应该在函数之前包含函数所依赖的任何常量,如头文件中的那样:
I
答案 2 :(得分:2)
您应该在使用库符号的标题(header.h
)中包含库头文件。
#include <complex>
最好将文件的所有依赖项包含在其自身中,而不是依赖于它们,否则将包含它们。也许你的header.h
被包含在库符号名称依赖关系不能通过其他包含间接解析的地方。
编辑:
在旁注中我不确定为什么在头文件本身中包含函数的定义。您应该将标题更改为仅包含声明:
<强> header.h 强>
#ifndef header
#define header
#include <complex>
typedef std::complex<double> cmp;
extern cmp I;
double function(double x);
#endif
添加另一个定义函数的源文件
<强> header.cpp 强>
#include "header.h"
double function(double x)
{
return 5*exp(I*x).real();
}
<强>的main.cpp 强>
#include <iostream>
#include "math.h"
#include <complex>
#include "header.h"
using namespace std;
cmp I(0.0,1.0);
int main()
{
cout << function(5.0) << endl;
return 0;
答案 3 :(得分:2)
更改header.h以包含此内容:
double function( std::complex<double> I, double x)
更改你的main.cpp,使其包含:
cout << function(I, 5.0) << endl ;
你的问题是因为在header.h
中你使用的变量I是不可见的。