简体   繁体   English

在C ++中创建对象数组

[英]creating an array of objects in c++

I'm trying to create an array of objects in c++. 我正在尝试在c ++中创建对象数组。

I'm creating a employee object, from my constructor in my company class here: 我正在从我公司类中的构造函数创建一个雇员对象:

employee obj(int tempIdNum, double tempBase, double tempSales, double tempRate);

emp[tempcount]=obj;  (this doesn't work?)

Emp is the name of the array which is defined here, located in my company h file. Emp是此处定义的数组的名称,位于我的公司h文件中。

 Employee emp[4]; 

sorry commission =employee..... here is my commission(employee) class cpp 抱歉,佣金=员工.....这是我的佣金(员工)类cpp

    using namespace std;


//----------------------------------------
//Name: default constructor
//Purpose: create a new object with attributes set to zero
//Parameters: none
//Returns: none
//----------------------------------------
Commission::Commission()
{
    //cout << "In default constructor of Commission class" << endl;
    idNum = 0;
    base  = 0.0;
    rate  = 0.0;
    sales = 0.0;
}


//----------------------------------------
//Name: initializing constructor
//Purpose: initialize all attributes
//Parameters:
//  idNum - new value for id Num
//  base -  new value for base amount
//  sales - new value for sales amount
//  rate -  new value for rate fraction
//Returns:  none  
//----------------------------------------       
Commission::Commission(int idNum, double base, double sales, double rate)
{
    //cout << "In initializing constructor of Commission class" << endl;
    this->idNum = idNum;    
    this->base  = base;
    this->sales = sales;
    this->rate  = rate;
}

//----------------------------------------
//Name: copy constructor
//Purpose: constructor a new object from an existing object
//Parameters: 
//  emp - current employee object
//Returns: none
//----------------------------------------
Commission::Commission(const Commission& emp)
{
    //cout << "In copy constructor of Commission class" << endl;
    idNum = emp.idNum;
    base  = emp.base;
    sales = emp.sales;
    rate  = emp.rate;
}

//----------------------------------------
//Name: operator=
//Purpose: The copy assignment method copies the rhs object
//  into the lhs object
//Parameters: 
//  rhs - object on the right hand side of the = sign
//Returns: nothing
//----------------------------------------
void Commission::operator=(const Commission& rhs)
{
    //cout << "In copy assignment of Commission class" << endl; 
    idNum = rhs.idNum;
    base  = rhs.base;
    sales = rhs.sales;
    rate  = rhs.rate;
}

//----------------------------------------
//Name: destructor
//Purpose: destruct object and print id num
//Parameters: none
//Returns: 
//----------------------------------------
Commission::~Commission()
{
    //cout << "In destructor of Commission class for id num: " << idNum << endl;
}

//----------------------------------------
//Name: setIdNum
//Purpose: set id num to a new value
//Parameters: 
//  newIdNum - new value for id num
//Returns: true if new id num is between 0 and 999, inclusively
//   otherwise false
//----------------------------------------
bool Commission::setIdNum(int newIdNum)
{
    if (newIdNum >= 0 && newIdNum <= 999)
    {
        idNum = newIdNum;
        return true;
    }
    else
        return false;
}

//----------------------------------------
//Name: setBase
//Purpose: set base to a new value
//Parameters: 
//  newBase - new value for base
//Returns: true if new base is greater zero; otherwise false
//----------------------------------------
bool Commission::setBase(double newBase)
{
    if (newBase > 0.0)
    {
        base = newBase;
        return true;
    }
    else
        return false;
}

//----------------------------------------
//Name: setRate
//Purpose: set the commission rate
//Parameters: 
// newRate - new commission rate as a percentage
//Returns: true if rate greater than zero and less than or equal to 0.20
//----------------------------------------
bool Commission::setRate(double newRate) 
{
    if (newRate > 0.0 && newRate <= 0.20)
    {
        rate = newRate;
        return true;
    }
    else
        return false;
}

//----------------------------------------
//Name: setSales
//Purpose: set sales to a new amount
//Parameters:
//  newSales - new amount of sales
//Returns: true if sales is greater than or equal to zero; otherwise false
//----------------------------------------
bool Commission::setSales(double newSales) 
{
    if (newSales >= 0.0)
    {
        sales = newSales;
        return true;
    }
    else
        return false;
}

//----------------------------------------
//Name: getIdNum
//Purpose: get the current id num
//Parameters: none
//Returns: current id num
//----------------------------------------
int Commission::getIdNum()  
{
    return idNum;
}

//----------------------------------------
//Name: getBase
//Purpose: get the current base amount of salary
//Parameters: none
//Returns: current base salary
//----------------------------------------
double Commission::getBase()  
{
    return base;
}

//----------------------------------------
 //Name: getRate
//Purpose: get the current commission rate as fraction
//Parameters: none
//Returns: current commission rate
//----------------------------------------
double Commission::getRate()
{
    return rate;
}

//----------------------------------------        
//Name: getSales
//Purpose: get current amount of sales
//Parameters: none
//Returns: current amount of sales
//----------------------------------------
double Commission::getSales()
{
    return sales;
}

//----------------------------------------
//Name: calcSalary
//Purpose: calculate commission as base + sales x commission rate
//Parameters: none
//Returns: amount of commission
//----------------------------------------
double Commission::calcSalary() 
{
    return (base + sales * rate);
}





and here is its .h


    #include <string>
using namespace std;

#ifndef Commission_H
#define Commission_H

class Commission
{
    private:
        int    idNum;   //id number of employee
        double base;    //base salary
        double rate;    //rate of commission as fraction
        double sales;   //sales on which commission rate applies

    public:
        //constructors
        Commission();               //default constructor
        Commission(int idNum, double base, double sales, double rate);  //constructor with idNum
        Commission(const Commission& orig);  //copy constructor

        //destructor
        ~Commission( );

        //copy assignment
        void operator=(const Commission& rhs);

        //mutators
        bool setIdNum(int idNum);        //set id num
        bool setBase(double base);       //set base salary
        bool setRate(double rate);       //set rate of commission
        bool setSales(double sales);     //set amount of sales for commission

        //accessors
        int    getIdNum();    //get id num;
        double getBase();     //get base salary
        double getRate();     //get commission rate
        double getSales();    //get sales for commission

        //calculate salary
        double calcSalary();  //calculate commission  
};        

#endif

As stated by the error message : the employee class must have an accessible operator= for this code to compile. 如错误消息所述: employee类必须具有可访问的operator=才能编译此代码。 As you already probably already know, the compiler will declare a copy-assignment operator if you don't provide one yourself. 您可能已经知道,如果您自己不提供一个拷贝赋值运算符,则编译器将声明它。

As for the reason of the error, I suspect that employee has const data members or anything else which makes the implicitly defined operator ill-formed (12.8/12) : 至于错误的原因,我怀疑employeeconst数据成员或其他任何使隐式定义的运算符格式不正确(12.8 / 12)的原因:

A program is illformed if the class for which a copy assignment operator is implicitly defined has: 如果隐式定义了副本分配运算符的类具有以下内容,则该程序将格式错误:

  • a nonstatic data member of const type, or const类型的非静态数据成员,或者
  • a nonstatic data member of reference type, or 引用类型的非静态数据成员,或
  • a nonstatic data member of class type (or array thereof) with an inaccessible copy assignment operator, or 具有不可访问的副本分配运算符的类类型(或其数组)的非静态数据成员,或
  • a base class with an inaccessible copy assignment operator. 具有不可访问的副本分配运算符的基类。

I presume you declared the array as 我假设您将数组声明为

employee emp[MAX];

so when you 所以当你

employee obj(int tempIdNum, double tempBase, double tempSales, double tempRate);
emp[tempcount] = obj

here's what you did: 这是您所做的:

  1. create an object obj 创建一个对象obj
  2. copy that object into emp[tempcount] object (think assignment operator). 将该对象复制到emp[tempcount]对象中(认为是赋值运算符)。

about this part i'm not completely sure, but when you do 关于这一部分,我不确定,但是当你这样做时

employee emp[MAX];

you actually create MAX employee objects (all using the default constructor). 您实际上创建了MAX雇员对象(全部使用默认构造函数)。

The construction seems wrong. 构造似乎是错误的。 Delete the type specifiers: 删除类型说明符:

Employee obj(tempIdNum, tempBase, tempSales, tempRate);

Or try: 或尝试:

emp[tempcount]=Employee(tempIdNum, tempBase, tempSales, tempRate);

Maybe, you need to implement one "operator =" constructor function, like this: 也许您需要实现一个“ operator =”构造函数,如下所示:

Employee& Employee::operator =(const Employee& otheremp)
{
     // to be done ... 
}

Last but not least. 最后但并非最不重要的。 Try this: 尝试这个:

employee array[100];

employee e(1,1.1,1.5,2.5);

array[0] = e;

should work 应该管用

Your copy assignment should not be void . 您的副本分配不应void Change it as follows: 进行如下更改:

Commission& Commission::operator=(const Commission& rhs)
{
    // bla bla
    return *this;
}

Or better yet, get rid of these all together. 或者更好的是,一起摆脱所有这些。 Compiler generated versions does the right thing and are simpler if all you are doing is copying members around (as in your case). 编译器生成的版本做正确的事情,并且如果您要做的只是复制成员(如您的情况),则版本会更简单。 This goes both for copy constructor, copy assignment, and the destructor. 这适用于复制构造函数,复制分配析构函数。 But make it explicit by adding a comment in your class declaration indicating that the class is using compiler generated copy constructor and assignment. 但是通过在类声明中添加注释来表明它是明确的,该注释表明该类正在使用编译器生成的副本构造函数和赋值。

Let me give one last unsolicited advice: Please take your time to properly format your question, and make it concise. 让我最后提出一个不请自来的建议:请花点时间正确格式化问题,并使其简洁。 The reason you didn't get an answer right away for such a simple misuse is cause you have a lot of gunk in your post. 您因为如此简单的误用而没有立即得到答案的原因是,您的帖子内容很多。 For example, spend 5 minutes to search/replace Commission with Employee to improve consistency, truncate all of the clearly irrelevant methods and documentation. 例如,花5分钟时间搜索/替换与Employee Commission ,以提高一致性,截断所有明显不相关的方法和文档。

It's not good to make array of objects. 数组对象不好。 Much better is to make an array of pointers to objects. 更好的方法是创建一个指向对象的指针数组。

employee ** array;
array = new employee[array_count]; // create an array of object pointers
for(int i=0; i<array_count; i++)
{
  array[i] = new employee( . . . your constructor parameters . . .);
  OR
  array[i] = *(anExistingEmployeeObject);
}

Please, don't forget to remove array safely: 请不要忘记安全地删除阵列:

for(int i=0; i<array_count; i++) delete array[i];
delete array;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM