2016-05-22 61 views
-3

在這段代碼中,我無法理解vecor是如何初始化的?C++:構造函數中的向量初始化

class Student : public Person{ 
private: 
    vector<int> testScores; 
public: 

    Student(string firstname,string lastname,int id,vector<int> scores):Person(firstname,lastname,id) 
    { 
      this->testScores=scores; 
    }  
    char calculate() 
    { 
     int sum=0; 
     char result; 
     for(int i=0;i<testScores.size();i++) 
     { 
      sum+=testScores[i]; 
     } 
     int res=sum/testScores.size(); 
     if(res<=100 && res>=90) 
     { 
      result='O'; 
     } 
     else if(res<90 && res>=80) 
     { 
      result='E'; 
     } 

回答

0

Student構造函數中,std::vector<int> testScores經由使用傳遞給Student構造的scores參數的內容賦值運算符(複製分配在這種情況下)初始化。

順便說一句,這是更好地傳遞scores(和std::string參數)通過常量引用的Student構造,以避免不必要的複製:

Student(const std::string& firstname, const std::string& lastname, const std::vector<int>& scores) 
    : Person(firstname, lastname) { 
    testScores = scores; // uses copy-assignment to initialise testScores 
} 
0

如何vecor被初始化?

它的默認隱式初始化(​​即由默認構造函數初始化)。爲了完整,它首先默認初始化,然後在構造函數的主體中複製賦值。

更有效的方法是使用member initializer list

class Student : public Person { 
private: 
    vector<int> testScores; 
public: 
    Student(string firstname, string lastname, int id, const vector<int>& scores) 
     :Person(firstname, lastname, id), testScores(scores) 
    { 
    } 
    ... 
}; 

它現在複製初始化(即由複製構造函數初始化)。