C++继承类没有显示默认构造函数

C++ inherit class shows no default constructor

本文关键字:显示 默认 构造函数 继承 C++      更新时间:2023-10-16

我正在创建几个类,我决定创建一个基本类,其他类将继承该基本类

这是我的基本类标题

#pragma once
#include "ImageService.h"
class State
{
public:
    State( ImageService& is );
    ~State();
    void Update();
};

不要担心方法,它们不是问题所在。所以现在我继续创建一个IntroState(头文件(

#pragma once
#include "State.h"
class IntroState : public State
{
public:
    IntroState(ImageService& imageService);
    ~IntroState();
    GameState objectState;
};

这是cpp文件

#include "IntroState.h"

IntroState::IntroState(ImageService& imageService)
{
    //error here
}

IntroState::~IntroState()
{
}

在构造函数中,它声明"没有类"State"的默认构造函数",现在我认为正在发生的事情是,State的默认构造函数需要一个传递给它的imageService引用。那么,我该如何将该构造函数中的imageService传递给State构造函数呢?

基类没有默认构造函数,这是在当前派生类构造函数中隐式调用的构造函数。您需要显式调用基的构造函数:

IntroState::IntroState(ImageService& imageService) : State(imageService)
{
}

常用方法:

IntroState::IntroState(ImageService& imageService)
    : State(imageService)
{
}

您也应该调用State的构造函数,如下所示:

IntroState::IntroState(ImageService& imageService)
    : State(imageService) {
}

提示:不要使用:

#pragma once,使用防护装置!

示例:

#ifndef GRANDFATHER_H
#define GRANDFATHER_H
class A {
    int member;
};
#endif /* GRANDFATHER_H */

你可以在wikipedia中阅读更多关于include guards的信息。

您可以看到#pragma不是标准的。两者均未出现在C++11(链接(中。