运算符=使用其他类的复制构造函数的过载失败

时间:2016-04-10 20:35:19

标签: c++ class operator-overloading

我正在尝试解决与重载分配运算符相关的问题,以便能够将一个列表分配给另一个。

我有两个班级:

class CarList{

    private:
    Car* head;
    void clear();

    public:
    CarList();
    ~CarList();
    CarList(const CarList & olist);
    CarList & operator= (const CarList & olist);

    void add_car(char* name, int number, int id);
    void remove_make(char* name);

};

class Car{

    private:
    char* make;
    int license_number;
    int owner_ID;
    Car* next;


    public:
    //constructor with data presentation
    Car(char* name, int number, int id);
    Car(const Car &car);
    //destructor with data presentation - for further use
    ~Car();
    //Rest of methods
    Car*& GetNext();
    char* GetMake();
    int GetLic();
    int GetID();
    int SetID(int id);
    void Print();
    };

我编写了以下方法来重载运算符:

CarList& CarList::operator= (const CarList & olist)
{
    clear();


    if (this == &olist) return *this; // detecting if target is same as source

    if(this->head != NULL) this->head=new Car(*olist.head);
    return *this;
}

调用Car copy构造函数:

Car::Car(const Car &car)
{
    this->make = new char[strlen(car.make)+1];
    strcpy(this->make, car.make);
    this->license_number = car.license_number;
    this->owner_ID = car.owner_ID;
    if (car.next != NULL)
        this->next = new Car(*car.next);
    else
        this->next = NULL;

}

但程序崩溃,我不知道为什么。 Carlist中的复制构造函数完全可以使用Car copy构造函数调用。

0 个答案:

没有答案