Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Missing type specifier - int assumed" cannot be solved by adding "return 0" to the main function

Tags:

c++

I am trying to figure out how the C++ key word "this" works. I followed the codes below, but it does not pass and show the error of "C4430: Missing type specifier, int assumed"

#include <iostream>
#include <string>

void PrintEntity(const Entity& e);

class Entity
{
public:
    int x, y;

    Entity(int x, int y)
    {
        this->x = x;
        this->y = y;

        PrintEntity(*this);
    }
};

void PrintEntity(const Entity& e)
{
    std::cout << "Entity" << std::endl;
}

int main()
{
    return 0;
}

I reviewed other similar questions, the solutions include adding "return 0" to the Main function or circular dependency. But I don't think these solutions apply for me. Please help me solve it, thanks!

like image 464
Qiang Yao Avatar asked Jan 26 '26 04:01

Qiang Yao


2 Answers

You are trying to declare PrintEntity's interface before the type of its one parameter is even declared, Entity.

You have to declare Entity first (without defining it, as its definition does use PrintEntity), before you use it in PrintEntity's declaration. You can do this by adding the line class Entity; before PrintEntity's declaration.

Once they're both declared, then the definitions are ok.

Important

As suggested in the comments, one more way to have the code compile/work, is to use a so called elaborated type specifier. With reference to the specific example, it is enough to change

void PrintEntity(const Entity& e);

to

void PrintEntity(const class Entity& e);
like image 66
Enlico Avatar answered Jan 27 '26 18:01

Enlico


Keep in mind that you don't have to define everything in the class all at once. Another option is to defer the definition of the constructor to after the definition of PrintEntity:

#include <iostream>
#include <string>

class Entity
{
public:
    int x, y;

    Entity(int x, int y);
};

void PrintEntity(const Entity& e)
{
    std::cout << "Entity" << std::endl;
}

Entity::Entity(int x, int y)
{
    this->x = x;
    this->y = y;

    PrintEntity(*this);
}

In this case you can get rid of the declaration of PrintEntity before the definition of the Entity class because you don't need it yet.

like image 21
Kevin Avatar answered Jan 27 '26 18:01

Kevin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!