"No default constructor exists "即使我不需要它

"No default constructor exists " even though I don't need it

本文关键字:不需要 exists No default constructor      更新时间:2023-10-16

我想问一下为什么我的编译器说"类对象不存在默认构造函数",即使我在该类中的任何地方都不需要它。

我不应该使用默认构造函数(明确表示我只需要一个带有参数 id 的参数化构造函数,完整的赋值可以在此链接上找到(

我试图想出它需要默认构造函数的原因,但我只是看不到它。就像,即使在标题中我也不需要对象的构造函数。

我也一直在搜索谷歌,但它也没有回答我的问题,或者如果是这样,我只是无法理解它并将其应用于我的例子。

这是我的对象。

#pragma once
#ifndef OBJECT_H
#define OBJECT_H
class Object
{
public:
Object(int aId);
virtual ~Object() {};
int getId() const;
double getX() const;
double getY() const;
void setX(double aX);
void setY(double aY);
private:
int id;
double x;
double y;
};
#endif //!OBJECT_H

这是我的对象.cpp

#include "Object.h"
Object::Object(int aId)
{
this->id = aId;
}
int Object::getId() const
{
return this->id;
}
double Object::getX() const
{
return this->x;
}
double Object::getY() const
{
return this->y;
}
void Object::setX(double aX)
{
this->x = aX;
}
void Object::setY(double aY)
{
this->y = aY;
}

这是我收到错误的类的头文件

#pragma once
#ifndef STATIC_OBJECT_H
#define STATIC_OBJECT_H
#include "Object.h"
enum class ObstacleType { Rock, SmallFlower, BigFlower };
class StaticObject : public Object {
public:
StaticObject(int aId, ObstacleType aObstacleType);
ObstacleType& getObstacleType();
private:
ObstacleType obstacleType;
};

#endif // !STATIC_OBJECT_H

在第 4 行以括号开头,我收到错误消息说"类对象中不存在默认构造函数",即使我在那里不需要它,即使我没有在块中放置任何东西,它也会一直这么说。

#include "StaticObject.h"
StaticObject::StaticObject(int aId, ObstacleType aObstacleType)
{   // <-- compilator error shows here
Object* obj = new Object(aId);
this->obstacleType = aObstacleType;
}
ObstacleType& StaticObject::getObstacleType() {
return this->obstacleType;
}

您的StaticObject构造函数没有调用任何非默认Object构造函数,因此将为基类调用默认构造函数,因此您当前的代码确实需要默认Object构造函数。