我编写了以下代码来测试具有静态成员的对象 vector 。我希望输出是:
1 2 3 4 5
6 7 8 9 10
但实际输出是:
1 2 3 4 5
6 6 6 6 6
看起来静态成员没有按预期递增。谁能解释一下?
// ==== test.h =====
using namespace std;
void test();
class Record{
static int total_number;
int id;
public:
Record();
void show() {std::cout << id << " "; }
};
// ==== test.cpp ====
#include "stdafx.h"
#include <iostream>
#include <vector>
#include "test.h"
using namespace std;
Record::Record(){
total_number += 1;
id = total_number;
}
void test(){
const int vec_length = 5;
Record a[vec_length];
for (unsigned int i=0; i<vec_length; i++)
a[i].show();
cout << endl;
vector<Record> vr(vec_length);
for (unsigned int i=0; i<vr.size(); i++)
vr[i].show();
cout << endl;
}
// ==== main.cpp =====
#include "stdafx.h"
#include <iostream>
#include "test.h"
using namespace std;
int Record::total_number = 0;
int _tmain(int argc, _TCHAR* argv[])
{
test();
return 0;
}
最佳答案
在 C++98/03 中,你的 vector 是用这个构造函数初始化的:
std::vector<Record> v(5, Record());
这将创建一个新对象,递增静态变量,然后制作该变量的五个 拷贝 以填充元素。总共有一个默认构造和五个复制构造,产生 6 6 6 6 6
在 C++11 中,构造函数是:
std::vector<Record> v(5);
这为五个元素创建空间并对它们进行值初始化,对于您的类型,这意味着为每个元素调用一次默认构造函数。总共有五个默认构造,产生 6 7 8 9 10
。
关于c++ - 如何构造对象 vector (具有静态成员),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7813260/