no default constructor exists for class x (inheritance) C++

匿名 (未验证) 提交于 2019-12-03 01:58:03

问题:

I have the following three headers:

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 d3dDevice );     ~Player();      void Initialize();     void Update();      float x;     float y;     float z;     float rotation;     float velocity;      ComPtr vertexbuffer;     ComPtr indexbuffer;     ComPtr texture[3]; protected:     const ComPtr d3dDevice; }; 

Why when I define a constructor for my PlayerStates class in my PlayerStates.cpp file do I get

no default constructor exists for class Player 

PlayerStates.cpp

#include "pch.h" #include "PlayerStates.h"  PlayerStates::PlayerStates() :      textureAmount( 3 ) { } 

回答1:

When you declare a non-default constructor for a class, the compiler does not generate a default one anymore. So you have to provide your own.

PlayerStates needs to call a default constructor of its base class Player in its own default constructor. So you either need to provide Player with a default constructor, or call it's non-default constructor from PlayerStates' default constructor initialization list.

This implicitly calls Player::Player().

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

This calls the single argument constructor:

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


回答2:

Player can't be created with out a ComPtr d3dDevice, so you're PlayerStates constructor is going to have to find one and pass it to Player.

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

Or, if that's not what you intended, turn the inheritance around like you mentioned in the comments.



易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!