"No default constructor exists "即使我不需要它
"No default constructor exists " even though I don't need it
我想问一下为什么我的编译器说"类对象不存在默认构造函数",即使我在该类中的任何地方都不需要它。
我不应该使用默认构造函数(明确表示我只需要一个带有参数 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
构造函数。
相关文章:
- 在两个类中共享相同的函数调用,并在不需要时避免空实例化
- 是否有类似std::lower_bound的函数,而不需要排序/分区输入
- 为什么output_editor Concept不需要output_e迭代器标记
- 在除法中不需要四舍五入
- 与C代码相比,为什么C++代码不需要"#define _POSIX_C_SOURCE 200809L"?
- 将值从另一个数组写入数组,不包括不需要的值 C++
- C++ 写入路径名中包含不需要的空字符的文件
- 是否有必要获取锁并在不需要唤醒线程时通知condition_variable?
- 使用 assimp 加载模型 - 不需要提升?
- 为什么转换函数声明不需要至少一个定义类型说明符
- 返回不需要的值的二叉搜索程序
- 当我不需要数据库中的所有值时,如何部分初始化 c++ 对象?
- C++:用户输入会产生不需要的行为
- 如何在不需要LIBCD.lib的情况下在Visual Studio 6中编译C项目
- 为什么python需要全局关键字而C/C++不需要?
- 将一个宏传递到另一个宏而不是直接传递内容时会出现不需要的额外"空"参数
- 为什么我们需要在 C++ 中检查空指针,而在 Java 中不需要?
- 为什么复制构造函数不需要检查输入对象是否指向自身?
- 为什么不需要在 C++20 中的依赖类型之前指定"typename"?
- "No default constructor exists "即使我不需要它