2017-10-18 5 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; 
}; 

당신이 요소로 CA::CA에 전달 된 매개 변수와 vector 멤버를 초기화 할 경우 기본 파일

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

답변

1

에서 .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() 
{ 

} 

에서 생성자의 구현 , (C++ 11 이후)을 사용할 수 있습니다. constructor of std::vectorstd::initializer_list 인 ini . 예 :

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