C++ 如何将std::array转换为类类型
我有下面的代码,我需要通过模板类创建一个对象数组。模板化类将接收另一个类作为其类型:C++ 如何将std::array转换为类类型,c++,c++11,C++,C++11,我有下面的代码,我需要通过模板类创建一个对象数组。模板化类将接收另一个类作为其类型: #include <iostream> #include <array> class B { public: B() {std::cout << "B Called" <<std::endl;} B(int y){std::cout << "B int Called" <<std::endl;} static
#include <iostream>
#include <array>
class B
{
public:
B() {std::cout << "B Called" <<std::endl;}
B(int y){std::cout << "B int Called" <<std::endl;}
static const int mysize;
};
const int B::mysize = 256;
template <typename anotherclass>
class A : public anotherclass
{
public:
A(){std::cout << "Called" << std::endl;}
static anotherclass* obj[anotherclass::mysize];
//static anotherclass[] init();
static std::array<anotherclass*,anotherclass::mysize> init();
};
template <typename anotherclass>
std::array<anotherclass*, anotherclass::mysize> A<anotherclass>::init ()
{
std::array<anotherclass*,256> objtemp[anotherclass::mysize];
for (int i = 0 ; i < anotherclass::mysize; i++)
{ objtemp[i] = new anotherclass(2); }
return objtemp;
}
//A<B> obj[256] = [] () {for (int i = 0 ; i < 256; i++) { obj[i] = new A<B>(2)}};
template <typename anotherclass>
anotherclass* A<anotherclass>::obj[anotherclass:: mysize] = A<anotherclass>::init();
int main()
{
A<B> a;
}
因为下面的语句,我期望B'构造函数被调用256次
objtemp[i] = new anotherclass(2)
我理解,因为我需要创建256个B类对象,它的构造函数应该被调用256次,这在我的例子中是不会发生的。那么,在本例中,我应该如何初始化静态对象数组呢-
template <typename anotherclass>
anotherclass A<anotherclass>::obj[anotherclass:: mysize] = A<anotherclass>::init();
模板
另一个类A::obj[anotherclass::mysize]=A::init();
上面的代码出了什么问题,或者我遗漏了什么?请考虑是使用C样式的数组还是
std::array
。后者似乎是一个更好的选择,因为在使用C++(11)时,不能简单地复制C样式数组
因此,将
objtemp
和obj
声明为std::array
s.只要决定是使用C型数组还是std::array
。后者似乎是一个更好的选择,因为在使用C++(11)时,不能简单地复制C样式数组
因此,将
objtemp
和obj
声明为std::array
s.将objtemp
声明为std::array
而不是与您从方法返回的类型相同的C样式数组。我已根据您的建议将代码更改为std::array
C型数组,即与您从方法返回的类型相同。我已根据您的建议更改了代码我已根据您的建议更改了代码-谢谢-但现在不确定为什么我会被提到错误只需按错误消息所说的做。这修复了它-模板anotherclass A::obj[anotherclass::mysize]=A::init();但是为什么B构造函数没有被调用256次呢?我已经按照你的建议修改了代码-谢谢-但是现在不确定为什么我会被提到错误-按照错误消息所说的去做。这修复了它-模板anotherclass A::obj[anotherclass::mysize]=A::init();但是为什么B构造函数没有被调用256次呢?
template <typename anotherclass>
anotherclass A<anotherclass>::obj[anotherclass:: mysize] = A<anotherclass>::init();
B Called
Called
objtemp[i] = new anotherclass(2)
template <typename anotherclass>
anotherclass A<anotherclass>::obj[anotherclass:: mysize] = A<anotherclass>::init();