类和结构,没有默认构造器

Classes & Structs, no default contructor

本文关键字:默认 构造器 结构      更新时间:2023-10-16

我正在尝试构建一个链表,它的元素属于我自己指定的类型。现在我不会撒谎,我在C++中没有太多OOP经验,但我只犯了一个错误。

我的链接列表:

#include "Vehicle.h"
#include "string"
using namespace std;
class LinkedList
{
private:
    struct Node
    {
        Vehicle data;
        Node* next;
    };
    Node* root;
    int noofitems;
public:
    LinkedList();
    int getNoOfItems();
    Vehicle getItemByIndex(int index);
    void addItem(Vehicle itemIn);
    void deleteItem();
    void insertItem(Vehicle itemIn);
    ~LinkedList();
};

构造函数和addItem()

LinkedList::LinkedList() : root(NULL), noofitems(0) {}
void LinkedList::addItem(Vehicle itemIn)
{
    Node* temp;
    temp = new Node();
    temp->data = itemIn;
    temp->next = this->root;
    this->root = temp;
}

我的编译器出现以下错误:CCD_ 1。现在我尝试给这个结构一个构造函数,如下所示:

struct Node
{
    Vehicle data;
    Node* next;
    Node() : next(NULL) {}
};

但在旧错误的基础上又出现了一个新错误:IntelliSense: no default constructor exists for class "Vehicle"。构造函数这个词开始看起来不对了,我真的很沮丧。提前谢谢。

顺便说一句,如果需要车辆类别的详细信息:

class Vehicle
{
protected:
    string make;
    string model;
    string regNo;
    int engineSize;
    bool rented;
public:
    Vehicle(string makeIn, string modelIn, string regNoIn, int engineSizeIn);
    string getMakeModel(); // return two values concatinated
    string getRegNo();
    int getEngineSize();
    bool getRented();
    void setRented(bool rentedIn);
    ~Vehicle();
};
Vehicle::Vehicle(string makeIn, string modelIn, string regNoIn, int engineSizeIn) :
                make(makeIn), model(modelIn), regNo(regNoIn), engineSize(engineSizeIn),
                rented(false)
{}
string Vehicle::getMakeModel()
{
    return make + " " + model;
}
string Vehicle::getRegNo()
{
    return regNo;
}
int Vehicle::getEngineSize()
{
    return engineSize;
}
bool Vehicle::getRented()
{
    return rented;
}
void Vehicle::setRented(bool rentedIn)
{
    rented = rentedIn;
}
Vehicle::~Vehicle(){}

Node有一个类型为Vehicle的成员。由于不能默认构造Vehicle,因此Node的默认构造函数被标记为已删除。您需要提供自己的默认构造函数,将Vehicle成员构造为某种状态,如

struct Node
{
    Vehicle data;
    Node* next;
    Node() : data("", "", "", 0), next(nullptr) {}
};

或者为类似的CCD_ 8提供默认构造函数

class Vehicle
{
    //...
public:
    Vehicle() = default;
    //...
};

这个错误不言自明。您尚未在error C2512: 'LinkedList::Node' : no appropriate default constructor available0类中显式初始化vehicle,如图所示:

struct Node
{
    Vehicle data;
    Node* next;
    Node() : next(NULL) {} // NO initialization for vehicle
};

编译器将尝试使用默认构造函数构造Vehicle,但没有找到。在您的车辆类中,您定义了一个接受参数的构造函数:

Vehicle(string makeIn, string modelIn, string regNoIn, int engineSizeIn);

因此,编译器将而不是为您生成一个。要解决此问题,您可以自己定义一个默认构造函数,也可以用单词default声明一个,这将迫使编译器也生成一个: