可以创建一个没有虚方法并且只有两个 double
的简单类吗?数据成员可以被安全地视为 std::complex<double>
的“直接替换”参数?
换句话说,假设有一个函数需要 std::complex<double>
数组,可以用前面提到的类来代替吗?
我尝试使用以下代码,它似乎在 Visual C++ 2010 SP1 编译器上运行良好。但是,我想知道这是否是特定于实现的,或者是否得到标准的正式支持。
可编译代码如下:
#include <iostream>
#include <complex>
#include <vector>
using namespace std;
class Point {
public:
Point(double x, double y)
: _x(x), _y(y) { }
// ... some non-virtual methods ...
private:
double _x;
double _y;
};
void f(const complex<double>* data, int count) {
for (int i = 0; i < count; ++i) {
cout << "(" << data[i].real() << ", "
<< data[i].imag() << ") ";
}
cout << endl;
}
int main() {
vector<Point> points;
points.push_back(Point(11.0, 22.0));
points.push_back(Point(33.0, 44.0));
points.push_back(Point(55.0, 66.0));
f(reinterpret_cast<const complex<double>*>(points.data()),
static_cast<int>(points.size()));
}
输出:
C:\Temp\CppTests>cl /EHsc /W4 /nologo test.cpp test.cpp C:\Temp\CppTests>test.exe (11, 22) (33, 44) (55, 66)
最佳答案
是的,它很安全。
Point
类不是 POD(因为构造函数),但它是一个“标准布局类”。 complex<double>
类型具有标准中定义的布局。
关于c++ - 包含两个 double 的类是否可以有效替代 std::complex<double> 参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23482501/