我正在尝试学习 C++ STL 中的 vector ...
我有一个 temp
类:
class temp
{
private :
int a;
public :
//temp() {}
temp(int a)
{
std::cout<<"ctor called"<<std::endl;
this->a=a;
}
void setA(int a)
{
this->a=a;
}
int getA()
{
return a;
}
};
现在,在主要部分,我写道:
int main() {
vector<temp> v;
v.resize(7,temp(5));
for(int i=0;i<7;i++) {
v[i].setA(i);
}
for(int i=0;i<7;i++) {
cout<<v[i].getA()<<"\t";
}
}
我得到的输出是
ctor called
0 1 2 3 4 5 6
我想知道为什么即使在创建类 temp 的 7 个不同对象时,构造函数也只被调用一次?
最佳答案
因为 vector 的元素是通过复制参数来初始化的。您传递的参数的创建是您的代码中唯一一次调用您编写的构造函数。您正在调用的 std::vector
中的构造函数描述为 here ,它是您调用的版本 (2)。
将复制构造器添加到您的类中以查看发生了什么:
temp(const temp& t)
{
std::cout<<"copy-ctor called"<<std::endl;
this->a = t->a;
}
在您的代码中,编译器为您生成了一个复制构造器,但显然没有调试输出,因此您看不到它。
关于c++ - 在 C++ 中调整 vector 大小时调用一次类构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15854237/