【发布时间】:2011-10-18 20:26:39
【问题描述】:
我编写了以下代码来测试具有静态成员的对象向量。我希望输出是:
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;
}
【问题讨论】:
-
而
Record::Record()的定义在哪里? -
看看复制构造函数的威力...
标签: c++ stl static vector constructor