After reading up on class tutorials on the C++ site, I have learned the following piece of code which I then tried to work with:
class CVector {
public:
int x,y;
CVector () {};
CVector (int,int);
CVector operator + (CVector);
};
CVector::CVector (int a, int b) {
x = a;
y = b;
}
After which I wrote the following code, in order to learn to program C++ classes efficiently and to write cleaner code:
class Player {
public:
string name;
int level;
};
Player::Player(int y) {
level = y;
}
However it gives me error C2511: ‘Player::Player(int)’ : overloaded member function not found in ‘Player’.
I have searched for the error but I did not find how to fix it. What’s wrong with this code?
You need to declare the single parameter construction:
Once you do this, there will no longer be a compiler synthesized default constructor, so if you need one, you would have to write your own. Also consider making the single parameter constructor
explicitif you do not want implicit conversions fromint.Also, prefer the constructor initialization list to assigning values in the constructor body, if possible. There are plenty of SO questions on that topic so I won’t elaborate here. This is how you would do it: