c++ - 如何构造对象 vector (具有静态成员)

标签 c++ stl static vector constructor

我编写了以下代码来测试具有静态成员的对象 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/

相关文章:

C++ 使用指针修改 vector

c++ - Win32 : How to trap left and right mouse button clicked at the same time

c++ - 如何使用STL获取中位数的索引?

c++ - C++20 范围适配器的递归应用导致编译时无限循环

boost - 在 Boost Jam 文件中将多个静态库组合成单个共享库

c++ - 用 C++ 字符从字母到数字

c++ - Debian 上的 Qt5 示例包

c++ - 为什么 std::map::operator[] 如此违反直觉?

C++ 初始化静态数组

c# - 线程安全静态类和构造函数