2017-10-18 134 views
1

是否可以使用構造函數的初始化列表初始化矢量成員。下面給出一些不正確的代碼。使用構造函數的參數初始化矢量成員

#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

如果你想初始化vector成員傳遞到CA::CA作爲元素的參數執行,您可以使用list initialization(自C++ 11以來),其中constructor of std::vector將採用std::initializer_list將用於ini tialization。例如

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" 
} 
+0

謝謝@songyuanyao – user18441

相關問題