如何在C ++中使用一些默认参数创建对象?

时间:2019-05-30 12:25:21

标签: c++ object default-constructor

我正在制作一个c ++项目,该项目要求我使用默认构造函数参数创建一个对象。问题是我不知道该怎么做。我目前能够创建带有参数的对象,但无法使用该构造函数创建带有空参数的对象。例如:用新车(id)代替新车(id,品牌,许可证)

我尝试了一些在基本情况下应该可以使用的东西,但是在这里我使用模板类来减小代码的大小。因此,我可以使用相同的功能来创建4个不同类型的对象(汽车,客户,租金或保险)。对于1种类型,我可以使用构造函数,只需编写New Car(0,“”,“”)即可将Car初始化为默认汽车。但是当涉及到不同的类型时,我不知道如何在同一函数中管理这些类型的参数。

如果我的列表中不存在默认对象,则该函数应返回默认对象:

T returnItem(int id){
    T* temp = head;
    while(temp){
        if(id == temp->id){
            T t = *temp;
            return t; //return the object
        }
        temp = temp->next;
    }
    T *ErrorT = new T(0); //only set the id of the default object
    return *ErrorT;
}

汽车构造函数:

Car::Car(int car_id, string car_brand, string car_license, char car_category, float car_rent, string car_status)
{
    this->id=car_id;
    this->brand=car_brand;
    this->license=car_license;
    this->category=car_category;
    this->carRentPrice=car_rent;
    this->status=car_status;
    this->next = NULL;
}

客户构造函数:

Customer::Customer(int customer_id, string customer_name, string customer_surname, string customer_address, string customer_phoneNb, string customer_email)
{
    this->id=customer_id;
    this->name=customer_name;
    this->surname=customer_surname;
    this->address=customer_address;
    this->phoneNb=customer_phoneNb;
    this->email=customer_email;
    this->next = NULL;
}

出租构造函数:

Car_rent::Car_rent(int rent_id, Customer customer, Car car, Insurance insurance, int carRentTime)
{
    this->id = rent_id;
    this->customerName = customer.name;
    this->customerSurname = customer.surname;
    this->carBrand = car.brand;
    this->license = car.license;
    this->status = car.status;
    this->rentTime = carRentTime;
    this->InsuranceName = insurance.name;
    this->InsurancePrice = insurance.price;
    this->rentPrice = calculatePrice(car.carRentPrice, rentTime);
    this->next = NULL;
}

当前,它仅返回有关我的构造函数的错误,该构造函数缺少参数(可能是因为定义不正确)。 我希望它返回一个ID类型为0且其他参数设置为字符串的List类型的对象,字符串的其他参数设置为“”,int或float的参数设置为0,而char的参数设置为''

0 个答案:

没有答案