类和结构,没有默认构造器
Classes & Structs, no default contructor
我正在尝试构建一个链表,它的元素属于我自己指定的类型。现在我不会撒谎,我在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 available
0类中显式初始化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
声明一个,这将迫使编译器也生成一个:
相关文章:
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 初始化具有非默认构造函数的std::数组项的更好方法
- 具有默认模板类型的默认构造函数的类型推导
- 如何使用非默认构造函数实例化模板化类
- 为什么不调用移动构造函数?(默认情况下只有构造器,没有别的)
- 有没有一种代码密度较低的方法来使用非默认构造函数初始化数组?
- 声明没有默认构造函数的字段
- 没有默认构造函数作为模板参数的自定义比较器
- C++17 没有默认构造函数的地图放置(私有默认构造函数)
- 默认构造函数不同声明的链接器错误
- 如何防止在基类初始化器中调用默认构造函数?
- 默认构造的地图迭代器以增量进入无限环路 - 绿色山丘编译器
- 如何将迭代器的默认构造值为迭代器作为函数中的默认参数
- C ,构造器中允许的参考参数默认值
- 类和结构,没有默认构造器
- 为什么自定义数据的 thrust::sort 需要一个默认的构造器,而 STL::sort 不需要?
- 如何初始化没有默认构造器的对象的成员数组?
- 迭代器默认构造函数和POD成员初始化
- C++类是否有默认构造器以及在以下情况下调用哪些构造函数?
- c++迭代器:没有合适的默认构造函数可用