指向复杂<double> sin </double>的指针

时间:2013-05-01 22:49:06

标签: c++ templates pointers std

我尝试编译这个简短的例子:

#include<iostream> 
#include<math.h>
#include<complex>

typedef double (*d_sin)(double);
typedef std::complex<double> (*c_sin)(std::complex<double>);

int main(void)
{

/* case 1 */
std::cout << "sin(pi/2)=" << sin(M_PI/2) << std::endl;

/* case 2 */
d_sin var = &sin;
std::cout << "sin(pi/2)=" << (*var)(M_PI/2) << std::endl;

/* case 3 */
c_sin var2 = &sin;
std::cout << "sin(pi/2)=" << (*var2)(M_PI/2) << std::endl;

return 0;
}

和错误:

$ g++ main.cpp && ./a.out 
main.cpp: In function ‘int main()’:
main.cpp:19:15: error: invalid conversion from ‘double (*)(double)throw ()’ to ‘c_sin {aka         std::complex<double> (*)(std::complex<double>)}’ [-fpermissive]
c_sin var2 = &sin;
           ^

为什么这个样本有错误?如何获得复杂案例的正确行为?非常感谢。

1 个答案:

答案 0 :(得分:1)

typedef std::complex<double> (*c_sin)(std::complex<double>);

typedef std::complex<double> (*c_sin)( const std::complex<double> & );

c_sin var2 = std::sin;