Reputation: 15
I have a problem and I would be happy to help.
i have a class player:
class Player{
public:
char Name[20];
Dice* dice;
int points;
Player(char name[20], Dice* dice){//constructor
for (int i = 0; i < 20; i++)
Name[i] = name[i];
points = 0;
}
and in my main i try:
Player* p1("aaa",d1);
Player* p2("ddd",d2);
the error:
error a value of type const char * cannot be used to initialize an entity of
type "Player*"
It's just part of the code but all the rest of the code is fine except for this one.
thank's.
Upvotes: 0
Views: 111
Reputation: 3305
Step 1: fixit
Player* p1
is jus a pointer to a Player
object, you need to point to an object:
Player playerP1("aaa",d1);
Player* p1(&playerP1);
So you have an object playerP1
, pointed by p1
Idem for p2
;
Step 2: go pro
You can also asign to a pointer dynamicaly using std::make_unique
or std::make_shared
:
auto p1 = std::make_shared<Player>("aaa",d1);
So you use the benefits of smart pointers and avoid using new
, and naked new( which is not recommended nowadays anymore).
Upvotes: 2
Reputation: 780818
You can use new
to construct an object dynamically and assign to a pointer:
Player *p1 = new Player("aaa", d1);
You should also change the constructor to take const char name[]
. Otherwise, you can't use a string literal as the argument.
And the loop that copies from name
to Name
needs to check for a null byte, otherwise you'll read past the end of "aaa"
.
Player(const char name[], Dice* dice){//constructor
for (int i = 0; i < sizeof(Name); i++) {
Name[i] = name[i];
if (name[i] == 0) {
break;
}
}
points = 0;
}
It would probably be better if you used std::string
instead of a fixed-length char
array.
=== Example added by phonetagger... === (I was working on an answer when Barmar posted this answer.)
#include <string>
class Player
{
public:
std::string Name;
Dice* dice;
int points;
//constructor
Player(std::string name, Dice* dice)
: Name(name), dice(dice), points(0)
{
}
};
int main()
{
Dice *d1 = new Dice();
Player* p1 = new Player("aaa", d1);
Player* p2 = new Player("ddd", d1);
}
Upvotes: 1
Reputation: 3360
Change your constructor to
Player(const char *name, Dice* dice)
Upvotes: -2