有没有办法访问复数类C++私有成员变量?

Is there any way to access private member variable of C++ complex number class?

本文关键字:成员 变量 C++ 访问 有没有      更新时间:2023-10-16

我正在使用标准C++库标题中内置的复数类std::complex。我在HLS工具中应用了代码。该工具无法访问该复杂类的私有成员变量。是否可以将其公开或我该怎么办?

Error: /usrf01/prog/mentor/2015-16/RHELx86/QUESTA-SV-AFV_10.4c-5/questasim/gcc-4.7.4-linux_x86_64/bin/../lib/gcc/x86_64-unknown-linux-gnu/4.7.4/../../../../include/c++/4.7.4/complex(222): 
error: 'fpml::fixed_point<int, 16u, 15u> std::complex<fpml::fixed_point<int, 16u, 15u> >::_M_real' is private

std::complex模板有点神奇:您具有将复数重新解释为两个标量的数组的显式权限。更一般地说,以下内容是有效的:

std::complex<float> a[10];
float* r = reinterpret_cast<float*>(a);
for (int i = 0; i != 20; ++i) std::cout << r[i] << 'n';

也就是说,您可以将复数数组视为实数两倍的数组。您可以使用此方法单独访问复数的元素。

但是,请注意以下约束([complex.numbers]p2(:

实例化除floatdoublelong double以外的任何类型的模板complex的效果是 未指定。

为了完整起见,访问成员的另一种方法是使用相应的getter,例如像这样

#include <complex>
int main()
{
std::complex<float> c;
c.real(1);
c.imag(2);
return c.real();
}