I'm new here and I'm learning C++. I can't find the answer to the following question:
There is a class Player
. What do the following phrases declare?
static Player * Player::bestPlayer = NULL;
and I'm also confused about:
string &a = b;
I'm new here and I'm learning C++. I can't find the answer to the following question:
There is a class Player
. What do the following phrases declare?
static Player * Player::bestPlayer = NULL;
and I'm also confused about:
string &a = b;
Concerning the first: it's hard to imagine a case where it would
be legal. (Perhaps if Player
is a namespace, but even then,
the first declaration of bestPlayer
must be within the
namespace. And can't be a definition, since this line is
a definition.)
What is probably meant is something like:
class Player
{
// ...
static Player* bestPlayer;
// ...
};
and then:
Player* Player::bestPlayer = NULL;
Note that the keyword static
must be in the class
definition, and not on the definition of the object itself, and
that the initialization can only be on the definition of the
object.
As for the second, it declares the symbol b
to be an alias to
a
. Anything you do to a
affects b
, and vice versa, and
anything you attempt to do will show them to be the same object.
(e.g. &a == &b
). This is called a reference, and while
there's rarely if ever any reason to use one as a local
variable, they are widely used as function arguments, and in
specific scenarios as return values.
These mean:
Static member of type Player*
is initialized to NULL
. Remove the keyword static
id the declaration is outside the class. If the declaration is inside, then remove the scope resolution operator.
A reference variable of type string
is created and assigned reference of b
as
string b;
string &a = b;
The first initializes a static member of class Payer to NULL (Note that member is a pointer). The second initializes a reference to a string with another string
Player * Player::bestPlayer = NULL;
initializes static
member bestPlayer
of type Player*
to NULL
. This is placed in some .cpp
file and it belongs to the declaration, which probably looks like this:
// Player.h
class Player {
public:
static Player* bestPlayer;
...
};
and to your second question, it declares a reference a
to std::string
object b
:
std::string b;
std::string &a = b;
Have a look at: What are the differences between a pointer variable and a reference variable in C++?
The code in the first snippet is a definition of a static member "bestPlayer" of a class Player.
Static member is shared between all instances if a class. It's not a member of the object (of the instance of the class), but of the class itself.
It's often used for creating singletons (google singleton pattern).
The code in the second snippet creates a reference named "a" to the string variable "b". Reference in c++ is something like an alias. It's similar to the pointer.