是否可以使用构造函数的初始化列表初始化向量成员。我在下面给出一些不正确的代码。
#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;
}
如果要使用作为元素vector
传递的参数来初始化成员,则CA::CA
可以使用列表初始化(自C ++ 11起),为此,将使用take的构造函数std::vector
std::initializer_list
进行初始化。例如
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"
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句