这确实在堆上创建了一个 Vector3D 对象数组。
每个向量都是通过调用 Vector3D 构造函数来创建的。
在 Vector3D 的默认构造函数中放置一点调试打印语句,并观察构造函数被调用的次数与数组中向量的次数相同。
例子:
#include <iostream>
using namespace std;
class C {
public:
C() { cout << "Hello default constructor here\n"; }
};
int main() {
C* cs = new C[5];
}
输出是:
Hello default constructor here
Hello default constructor here
Hello default constructor here
Hello default constructor here
Hello default constructor here
如果您的类没有默认构造函数,则无法一次性分配数组(感谢@Everyone 的评论),因此在这种情况下,请考虑使用std::vector 或std::array 并添加您的Vector3D动态对象——甚至“静态”!示例:
#include <iostream>
#include <vector>
using namespace std;
class Vector3D {
double i, j, k;
public:
Vector3D(double i, double j, double k): i(i), j(j), k(k) {}
};
int main() {
vector<Vector3D> v = {
Vector3D(3, 4, 5),
Vector3D(6, 8, 10),
Vector3D(7, 24, 25)
};
v.push_back(Vector3D(1, 2, 3));
cout << v.size() << '\n';
}
这会输出 4。
您还可以使向量包含指向 Vector3D 对象的指针。