Reputation: 199
I have a struct, player, which is as follows:
struct player {
string name;
int rating;
};
I'd like to modify it such that I declare the struct with two arguments:
player(string, int)
it assigns the struct's contents with those values.
Upvotes: 5
Views: 29847
Reputation: 5181
You are allowed to declare a constructor for your player
struct:
struct player {
string name;
int rating;
player(string n, int r) :
name(n),
rating(r)
{
}
};
In C++ one of the few differences between classes and structs is that class members default to private, while struct members default to public.
Upvotes: 4
Reputation: 25053
Although (as has been pointed out), you can simply add a constructor:
struct player() {
string name;
int rating;
player(string Name, int Rating) {
name = Name; rating = Rating;
}
};
Is there some reason you don't want to make it a class?
class player() {
public:
string name;
int rating;
player(string Name, int Rating) {
name = Name; rating = Rating;
}
};
Upvotes: 5
Reputation: 62975
Aside from giving your type a constructor, because as-shown it is an aggregate type, you can simply use aggregate initialization:
player p = { "name", 42 };
Upvotes: 8
Reputation: 104698
you would use the constructor, like so:
struct player {
player(const string& pName, const int& pRating) :
name(pName), rating(pRating) {} // << initialize your members
// in the initialization list
string name;
int rating;
};
Upvotes: 8