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!
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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With