I am a newcomer to learning C++. I just tried to run the following code in vs code, but it reported an error
#include <iostream>
using namespace std;
class Entity
{
public:
Entity()
{
cout << "default" << endl;
}
Entity(int x)
{
cout << x << endl;
}
Entity(Entity &e)
{
cout << "copy" << endl;
}
Entity &operator=(const Entity &e)
{
cout << "assignment" << endl;
return *this;
}
};
int main(void)
{
Entity e = Entity(8);
}
The error is cannot bind non-const lvalue reference of type 'Entity&' to an rvalue of type 'Entity' Entity e = Entity(8);
I am searching for a long time on net. Some people say this is because compiler created temporary objects cannot be bound to non-const references, so adding const modifier will work.
Entity(const Entity &e)
{
cout << "copy" << endl;
}
It seems that I am initializing an object with the copy constructor, otherwise the compiler should not report an error. But the fact is I'm using the parameterized constructor to do that. What puzzles me is why initialization in this way has something to do with the copy constructor?