的构造函数B
是可以的,但是你调用的方式push_back()
不是:
btest.push_back(B(A));
你应该做这个:
btest.push_back(B(test));
B
此外,不需要显式构造对象,因为您的构造函数未标记为explicit
:
btest.push_back(test);
还要考虑使用自动内存管理而不是原始指针(std::vector<>
而不是数组,智能指针而不是指针)。这样,您将避免由于忘记这一点而导致内存泄漏:
delete test;
撇开泄漏不谈,最糟糕的是你的代码也有未定义的行为,因为它使用了未初始化变量的值(循环A
内的成员变量)。for
最后,你不应该:
在类定义中使用 after 类名。这就是您可以在 C++11 中重写代码的方式:
#include <vector>
#include <cstdio>
struct A // Do not use ":" here, that's for introducing inheritance,
// which you are not using in your example.
{
float mem1 = 0.0; // In C++11, you can specify default initialization
int mem2 = 0; // for your member variables this way. In C++03 you
// would have to define a default constructor which
// initializes your member variables to the desired
// value.
};
struct B
{
std::vector<A> Aarr;
// ^^^^^^^^^^^^^^
// Prefer using standard containers over dynamically allocated arrays, as
// it saves your from taking care of memory management and avoids leaks.
explicit B(size_t s): Aarr(s) { }
// ^^^^^^^^
// It is usually a good idea to mark constructors which take on argument
// and are not copy constructors as explicit, to avoid awkward implicit
// conversions.
};
int main()
{
std::vector<B> btest;
btest.push_back(B(5));
// ^^^^
// We need to explicitly construct an object of type B,
// because we have marked B's constructor as explicit.
for(int i=0; i<5; i++)
{
std::printf(
"mem1: %f, mem2: %i \n",
btest[0].Aarr[i].mem1,
btest[0].Aarr[i].mem2
// ^
// You had "mem1" here.
);
}
}