【问题标题】:C++ inherit class shows no default constructorC ++继承类显示没有默认构造函数
【发布时间】:2014-05-22 20:28:25
【问题描述】:

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

这是我的基本类头

#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 引用。那么如何将这个构造函数中的图像服务传递给状态构造函数呢?

【问题讨论】:

  • +1 表示格式不错,实际上几乎是自己回答问题。

标签: c++ inheritance


【解决方案1】:

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

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

}

【讨论】:

  • 我确实只是输入了它并且它工作了 :D,尽管为快速回复干杯
【解决方案2】:

通常的方式:

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

【讨论】:

  • 我确实只是输入了它并且它工作了 :D,尽管为快速回复干杯
【解决方案3】:

你也应该调用State的构造函数,像这样:

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

提示:不要使用:

#pragma once,使用警卫!

例子:

#ifndef GRANDFATHER_H
#define GRANDFATHER_H

class A {
    int member;
};

#endif /* GRANDFATHER_H */

您可以在wikipedia 中阅读有关包含保护的更多信息。

您看到#pragma 不是标准。两者都没有成为C++11 (link)。

【讨论】:

    猜你喜欢
    • 2017-10-04
    • 2011-04-12
    • 2015-07-09
    • 2011-05-20
    • 2014-06-08
    • 1970-01-01
    • 1970-01-01
    • 2016-03-24
    • 2015-12-10
    相关资源
    最近更新 更多