I get an error in the c ++ class constructor

1
#include <windows.h>
#include <stdio.h>
namespace textTDengine{
typedef const char* spr;
enum direction{up,down,left,right};
struct vector2{
    float x;
    float y;


    vector2(float x,float y){
        this->x = x;
        this->y = y;
        }

        COORD vector_to_coord(){
            COORD result;
            result.X = x;
            result.Y = y;
            return result;
        }


};


class object{
    spr sprite;

    vector2 position;

    direction dir;
    public:
    void draw_on_screen(){
        HANDLE hcon;
        hcon = GetStdHandle(STD_OUTPUT_HANDLE);

        SetConsoleCursorPosition(hcon,position.vector_to_coord());

        printf(sprite);
    }
    //aqui en el constructor me da error
    object(spr a_sprite,vector2 pos){
        sprite = a_sprite;
        position = pos;

    }

    void SetPos(vector2 pos){
        position = pos;
    }

    void SetDir(direction d_dir){
        dir = d_dir;
    }

    void SetSpr(spr a_sprite){
        sprite = a_sprite;

    }



};      

}
    
asked by pmstd 30.05.2017 в 02:56
source

1 answer

1

In C ++ the compiler is able to create a series of constructors ... as long as certain circumstances exist. For example, for the compiler to create the default constructor, it is necessary that:

  • No own constructor has been implemented
  • The default constructor has not been explicitly implemented

The first rule is not met in the case of vector2 :

struct vector2{
    vector2(float x,float y){ // <<--- Constructor propio
        this->x = x;
        this->y = y;
        }
};

Since you have not declared the constructor by default and the compiler is not going to create that constructor then an error occurs here:

class object{

    vector2 position; // (1)

    object(spr a_sprite,vector2 pos){ // (2)
        sprite = a_sprite;
        position = pos; // (3)
    }

The comments refer to the following:

  • Class object has a member variable of type vector2
  • By virtue of the previous point, in the constructor of object you must call some constructor of vector2 , since no constructor has been invoked explicitly the compiler tries to call the constructor by default. As said constructor is not found, the error is caused.
  • This is nothing more than a post-construction assignment.
  • The solution is to invoke the constructors instead of making assignments:

    object(spr a_sprite,vector2 pos)
      : sprite(a_sprite), position(pos) // Llamadas a constructores
    {
    }
    
        
    answered by 30.05.2017 в 08:48