1

父类是车辆,子类是汽车。必须为所有构造函数使用初始化列表,这对我来说是一个挑战。对于我目前的情况,我不断收到以下错误:

car.cpp:7:1: error: redefinition of 'Car::Car()'
Car::Car()
^
In file included from car.cpp:3:0:
car.h:12:5: note: 'Car::Car()' previously defined here
     Car() : Vehicle("NoID", -1, "NoMake", "NoModel", "NoColor") {}
     ^

作为一个新手,我对基本的初始化列表有点熟悉,但在子类中使用它们时就不熟悉了。如果不是很明显,这是为了分配;我只是在寻找诊断上述错误的帮助,而不是完整的解决方案。

车辆.h

#ifndef VEHICLE_H
#define VEHICLE_H

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

class Vehicle
{
protected:
    /* Each of these data item represent something any type of vehicle
    will have, so it makes sense these would be in the base class. */

    // added a parent constructor so child classes can use
    // these variables in initializer list
    Vehicle(string id, int year, string make, string model,
            string color) : id(id), year(year), make(make),
                            model(model), color(color) {}
    string id;
    int year;
    string make;
    string model;
    string color;

public:
    Vehicle();
    // Vehicle(string id, int year, string make, string model, string color);
    Vehicle(ifstream &infile);
    // virtual ~Vehicle();
    string getID();
    void setID(string ID);
    virtual void printInfo(ofstream &out);
};

#endif

汽车.h

#ifndef CAR_H
#define CAR_H

#include <iostream>
#include <string>
#include "vehicle.h"
using namespace std;

class Car : public Vehicle
{
private:
    Car() : Vehicle("NoID", -1, "NoMake", "NoModel", "NoColor") {}
    int doors;
    string paymentType;

public:
    // Car();
    Car(string id, int year, string make, string model, string color, int doors, 
string paymentType);
    Car(ifstream &infile);

    int getDoors();
    void setDoors(int numdoors);

    string getPaymentType();
    void setPaymentType(string pt);

    void printInfo(ofstream &out);
};

#endif

汽车.cpp

#include <iostream>
#include <string>
#include "car.h"
#include "vehicle.h"
using namespace std;

Car::Car()
{
    // default constructor initialization list?
}

Car::Car(string id, int year, string make, string model,
         string color, int doors, string paymentType)
{
    // parameterized constructor
}

Car::Car(ifstream &infile)
{
    // regular constructor i think
}

int Car::getDoors()
{
    return doors;
}

void Car::setDoors(int numdoors)
{
    doors = numdoors;
}

string Car::getPaymentType()
{
    return paymentType;
}

void Car::setPaymentType(string pt)
{
    paymentType = pt;
}

void Car::printInfo(ofstream &out)
{
// unfinished
} 
4

1 回答 1

0

您在这里声明并定义了您的构造函数

Car() : Vehicle("NoID", -1, "NoMake", "NoModel", "NoColor") {}

所以cpp文件中的定义是第二个定义,是非法的

Car::Car()
{
    // default constructor initialization list?
}

如果您想将实现移动到 cpp 文件,则将标头更改为仅包含声明

// car.h
class Car : public Vehicle
{
    Car();
    ...
};

// car.cpp
Car::Car()
: Vehicle("NoID", -1, "NoMake", "NoModel", "NoColor")
{
    // default constructor initialization list?
}
于 2020-04-16T18:51:12.840 回答