对于类x(继承)C ++,不存在默认构造函数

时间:2014-01-08 21:32:02

标签: c++

我有以下三个标题:

IBaseStates.h

class IBaseStates
{
public:
    enum STATE;

    virtual void Update( STATE state ) = 0;
};

PlayerStates.h

#pragma once

#include "IBaseStates.h"
#include "Player.h"

class PlayerStates : public IBaseStates, public Player
{
public:
    enum STATE {
        FLYING,
        FALLING
    };

    int textureAmount;

    PlayerStates();
    ~PlayerStates( );

    void Update( STATE state );
};

Player.h

#pragma once

#include "StructVertex.h"
#include "SquareVertices.h"
#include "WICTextureLoader.h"

using namespace Microsoft::WRL;
using namespace DirectX;
//using namespace DirectX;

class Player : public SquareVertices
{
public:
    Player( ComPtr<ID3D11Device1> d3dDevice );
    ~Player();

    void Initialize();
    void Update();

    float x;
    float y;
    float z;
    float rotation;
    float velocity;

    ComPtr<ID3D11Buffer> vertexbuffer;
    ComPtr<ID3D11Buffer> indexbuffer;
    ComPtr<ID3D11ShaderResourceView> texture[3];
protected:
    const ComPtr<ID3D11Device1> d3dDevice;
};

为什么我在PlayerStates.cpp文件中为我的PlayerStates类定义构造函数时,我得到

no default constructor exists for class Player

PlayerStates.cpp

#include "pch.h"
#include "PlayerStates.h"

PlayerStates::PlayerStates()
: 
    textureAmount( 3 )
{
}

2 个答案:

答案 0 :(得分:12)

当您为类声明非默认构造函数时,编译器不再生成默认构造函数。所以你必须提供自己的。

PlayerStates需要在其自己的默认构造函数中调用其基类Player的默认构造函数。因此,您需要为Player提供默认构造函数,或者从PlayerStates'默认构造函数初始化列表中调用它的非默认构造函数。

这隐式调用Player::Player()

PlayerStates::PlayerStates() : textureAmount( 3 ) {}

这会调用单个参数构造函数:

PlayerStates::PlayerStates() : Player(someComPtr), textureAmount( 3 ) {}

答案 1 :(得分:1)

无法使用Player创建

ComPtr<ID3D11Device1> d3dDevice,因此您PlayerStates构造函数必须找到一个并将其传递给Player。< / p>

PlayerStates::PlayerStates()
: 
  Player( globalD3DDevice ),
  textureAmount( 3 )
{
}

或者,如果那不是你想要的,那就像你在评论中提到的那样转换继承。