' GameObject':没有合适的默认构造函数可用

时间:2017-03-23 02:59:43

标签: c++ inheritance parent-child default-constructor

我试图用游戏对象创建一个游戏,包括瓷砖,玩家,敌人和墙壁。我试图将我的类Character(Parent以及另外两个类Player和Enemy)添加到基类GameObject。当我尝试为Characters创建构造函数时,我在Character.cpp文件中得到了C2512错误。谁能指出我可能做错了什么?提前谢谢。

Characters.h

#ifndef CHARACTERS_H
#define CHARACTERS_H

#include <cstdlib>    
#include <ctime>      /*cstdlib and ctime are used to help with the pseudo randomness for events*/
#include <cstdio>   /*allows remove function*/
#include <iostream>
#include <fstream>
#include <sstream>
#include <array>
#include <string>
#include <vector>
#include "GameObject.h"

using namespace std;

class Character : public GameObject{
public:
    Character();
    ~Character();
    virtual void attack(vector<Character *>&characters) = 0;
    void set_values(string nam, int hp, int str, int mag) {
        name = nam;
        health = hp;
        strength = str;
        magic = mag;
    };
    string name;
    int health;
    int strength;
    int magic;

};


#endif

GameObject.h

#ifndef GAMEOBJECCT_H
#define GAMEOBJECT_H

#include "Direct3D.h"
#include "Mesh.h"
#include "InputController.h"

class GameObject {
protected:
    Vector3 m_position;
    float m_rotX, m_rotY, m_rotZ;
    float m_scaleX, m_scaleY, m_scaleZ; //Not really needed for A1.
    //Used for rendering
    Matrix m_world;
    Mesh* m_mesh;
    Texture* m_texture;
    Shader* m_shader;
    InputController* m_input; //Might have enemies who react to player input.

    float m_moveSpeed;
    float m_rotateSpeed;

public:
    //Constructor
    GameObject(Mesh* mesh, Shader* shader, InputController *input, Vector3 position, Texture* texture);
    ~GameObject();
    void Update(float timestep);
    void Render(Direct3D* renderer, Camera* cam);

Characters.cpp

#include "Characters.h"
#include <cstdlib>    
#include <ctime>      /*cstdlib and ctime are used to help with the pseudo randomness for events*/
#include <cstdio>   /*allows remove function*/
#include <iostream>
#include <fstream>
#include <sstream>
#include <array>
#include <string>
#include <vector>
using namespace std;

void Character::attack(vector<Character *>&characters) {};

Character::Character() {

};
Character::~Character() {};

2 个答案:

答案 0 :(得分:1)

您的GameObject应该有一个默认构造函数(没有参数的构造函数)。

因为在Character::Character()中,编译器将生成对GameObject的默认构造函数的调用。

如果没有为类GameObject实现任何构造函数,编译器将为它生成一个空的默认构造函数。但是你已经为类GameObject实现了一个构造函数,所以编译器不会这样做。您应该自己为它提供默认构造函数。

答案 1 :(得分:1)

Character::Character() {};

相当于

Character::Character() : GameObject() {};

由于GameObject没有默认构造函数,编译器会生成错误。除非GameObject的用户定义构造函数使用的所有参数都有合理的默认值,否则应更改Character以使用户定义的构造函数接受构造{{{{}所需的所有参数。 1}}。

GameObject

并将其实施为:

Character(Mesh* mesh,
          Shader* shader,
          InputController *input,
          Vector3 position,
          Texture* texture);
相关问题