2014-10-17 128 views
0

我寫了下面employee類:C++數組,數組賦值

#include<iostream> 
#include<string> 
using namespace std; 

class employee 
{ 
    private: 
     int id; 
     int salaries[12]; 
     int annualS; 
     string name; 

    public: 
     employee(int id2, string name2, int array[12]) 
     { 
      id = id2; 
      name=name2; 
      salaries = array; //here where the error occurred. 
     } 
     ~employee() 
     { 
      cout<<"Object Destructed"; 
     } 

     employee() 
     { 
      id = 0; 
      name="Mhammad"; 
     } 

     int annulalSalary() 
     { 
      for(int i=0; i<12; i++) 
      { 
       annualS+=salaries[i]; 
      } 
      return annualS; 
     } 
     int tax() 
     { 
      return (annualS*10/100); 
     } 
}; 

void main() 
{ 
    int salaries[12]; 
    for(int i=0; i<12; i++) 
    { 
     cin>>salaries[i]; 
    } 

    employee Mohammad(10,"Mohammad",salaries); 

    cout<< Mohammad.annulalSalary(); 
    cout<< Mohammad.tax(); 
} 

...但是當我編譯它,編譯器返回以下錯誤:

cannot convert from 'int []' to 'int [12]' 

誰能幫我解決這個問題?

+5

使用'std :: array '或'std :: vector ',它們有'operator ='重載(等等),這意味着你不必自己寫分配代碼。 – Borgleader 2014-10-17 19:57:57

+0

問題是你的構造函數中的參數。工資不能被聲明爲12號。相反,使用'int * salaries'。但是,是的,你應該使用矢量,更好,更安全 – WindowsMaker 2014-10-17 20:06:29

回答

0

只能在C++中使用=運算符才能複製整個數組。你有兩個選擇。

  1. 過載=操作 或
  2. 使用像這樣循環到一個陣列的每個元素複製到另一個

    的for(int i = 0;我< 12; i ++在) 薪金[ I] =陣列[I];

在不同的筆記上不要在代碼中使用像12這樣的幻數。

0

代替C數組中,使用C++ std::array<>,像這樣:

class employee { 
    //... 
    std::array<int, 12> salaries; 
    //... 
}; 

,當然你必須包括<array>了。和聲明構造是這樣的:

employee(int id2, string name2, std::array<int, 12> const & array) 
{ 
    //... 
} 

(或掉落const &如果你不知道它們是什麼,或者他們不需要它們。)

0

您無法通過分配複製陣列。您需要單獨複製每個元素。使用std::copy

std::copy(array, array+12, salaries); 

或者使用std::vector<int>std::array<int, 12>由Borgleader其不被複制的分配建議。

+0

@ Jarod42謝謝。忘記了'std :: size_t'參數。 – Mahesh 2014-10-17 20:21:21

-1

使用向量類!

但要解決問題:

int salaries[12]應該int* salaries employee(int id2, string name2, int array[12])應該employee(int id2, string name2, int* array)

不過你可能會分配的內存和內存設計缺陷外引用的東西的問題。 使用向量!