使用构造函数的参数初始化vector成员

时间:2017-10-18 02:47:30

标签: c++ vector initialization

是否可以使用构造函数的初始化列表初始化vector成员。我在下面给出了一些错误的代码。

#ifndef _CLASSA_H_
#define _CLASSA_H_

#include <iostream>
#include <vector>
#include <string>

class CA{
public:
    CA();
    ~CA();

private:
    std::vector<int> mCount;
    std::vector<string> mTitle;
};

.cpp文件中构造函数的实现

// I want to do it this way
#pragma once

#include "classa.h"


// Constructor
CA::CA(int pCount, std::string pTitle) :mCount(pCount), mTitle(pTitle)
{

}


// Destructor
CA::~CA()
{

}
主文件中的

#include "classa.h"
int main()
{
    CA A1(25, "abcd");
    return 0;
}

1 个答案:

答案 0 :(得分:2)

如果要使用传递给vector的参数作为元素初始化CA::CA成员,可以使用list initialization(自C ++ 11起),{{{ 3}}取std::initializer_list将用于初始化。 e.g。

CA::CA(int pCount, std::string pTitle) :mCount{pCount}, mTitle{pTitle}
//                                            ~      ~        ~      ~
{
    // now mCount contains 1 element with value 25,
    //     mTitle consains 1 element with value "abcd"
}