没有默认构造函数?

时间:2016-03-30 19:19:30

标签: c++ constructor not-exists

#include <iostream>
using namespace std;

//To know the car's make, model, color, license number, and the number of minutes the car has been parked
class ParkedCar
{
    string make, model, color, license_number;
    int minutes;
public:
    ParkedCar(string make = "...", string model = "...", string color = "...",
        string license_number = "...", int minutes = 0) : make{ make }, model{model},
        color{color}, license_number{license_number}, minutes{minutes} { this->make = make; }
};

//To know the number of minutes of parking time that has been purchased
class ParkingMeter
{
    int purchased_minutes;
public:
    ParkingMeter(int purchased_minutes) { this->purchased_minutes = purchased_minutes; }
};

//To report the make, model, color, and license number of the illegally parked car
//To report the amount of the fine, which is $25 for the first hour, or part of an
    //hour that the car is illegally parked, plus $10 for every additional hour or
    //part of an hour that the car is illegally parked
//To report the name and badge number of the police officer issuing the ticket
class ParkingTicket
{
    ParkedCar car;
    ParkingMeter meter;
    PoliceOfficer officer;
public:
    ParkingTicket(const ParkedCar &car, const ParkingMeter &meter, const PoliceOfficer &officer)
    {
        this->car = car;
        this->meter = meter;
        this->officer = officer;
    }
};

//To know the officer's name and badge number
//To examine a ParkedCar object and a ParkingMeter object, and determine whether the car's time has expired
//To issue a prking ticket (generate a ParkingTicket object) if the car's time has expired
class PoliceOfficer
{
    string name;
    int badge_number;
    ParkedCar car;
    ParkingMeter meter;
public:
    PoliceOfficer(const ParkedCar &car, const ParkingMeter &meter, string name = "...", int badge_number = 000000)
    {

        this->car = car;
        this->meter = meter;
    }

};

所以我正在为学校制作这个文件,一切都很顺利,直到我进入ParkingTicket和PoliceOfficer课程。我试图定义这些构造函数,他们都告诉我没有其他类的默认构造函数。我该如何解决这个问题?谢谢! :)

2 个答案:

答案 0 :(得分:4)

既然你的构造函数

PoliceOfficer(const ParkedCar &car, const ParkingMeter &meter, string name = "...", int badge_number = 000000)
{

    this->car = car;
    this->meter = meter;
}

没有carmeter的成员初始值设定项(正文中的作业不算作初始值设定项),就好像你写了{{1}一样初始化程序,它试图调用不存在的默认构造函数。您应该显式编写成员初始值设定项:

: car(), meter()

(另外,你的对象模型有点滑稽:警察有一个停车计时器?)

答案 1 :(得分:0)

首先,# BEGIN WordPress <IfModule mod_rewrite.c> RewriteEngine On RewriteBase /wpfiles/ RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /wpfiles/index.php [L] </IfModule> # END WordPress (如你所示) 有一个默认构造函数(所有参数都有默认值,因此可以不带参数调用。

真正的解决方案是更改构造函数使用以使用初始化列表:

ParkedCar