是否可以使用构造函数的初始化列表初始化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;
}
答案 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"
}