2014-10-17 229 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)

不过你可能会分配的内存和内存设计缺陷外引用的东西的问题。 使用向量!