1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
|
#include <iostream>
#include <initializer_list>
enum Pet {Dog, Bird, Cat}; // etc...
enum Colour {Black, Brown, Yellow}; // etc...
struct MyPetsData {
Pet pet;
int catAge, dogAge; // etc...
double catWeight, dogWeight; // and many more
Colour birdColour, dogColour, catColour; // etc...
bool birdCanFly, dogWillBite; // etc...
std::string birdName; // etc...
// ...
MyPetsData (Pet p, int a, double b, Colour c): pet (p) {
switch (p) {
case Cat: catAge = a; catWeight = b; catColour = c; break;
case Dog: dogAge = a; dogWeight = b; dogColour = c; dogWillBite = false; break;
}
}
MyPetsData (Pet p, int a, double b, Colour c, bool d): pet (p) {
switch (p) {
case Dog: dogAge = a; dogWeight = b; dogColour = c; dogWillBite = d; break;
}
}
MyPetsData (Pet p, Colour a, bool b, const std::string& c): pet (p) {
switch (p) {
case Bird: birdColour = a; birdCanFly = b; birdName = c; break;
}
}
// etc...
};
struct MyPets {
int catAge, dogAge; // etc...
double catWeight, dogWeight; // and many more
Colour birdColour, dogColour, catColour; // etc...
bool birdCanFly, dogWillBite; // etc...
std::string birdName; // etc...
// ...
MyPets (const std::initializer_list<MyPetsData>& petsList) {
for (const MyPetsData& x: petsList)
{
switch (x.pet) {
case Cat: catAge = x.catAge; catWeight = x.catWeight; catColour = x.catColour; break;
case Dog: dogAge = x.dogAge; dogWeight = x.dogWeight; dogColour = x.dogColour; dogWillBite = x.dogWillBite; break;
case Bird: birdColour = x.birdColour; birdCanFly = x.birdCanFly; birdName = x.birdName; break;
// etc...
}
}
}
};
void listOutMyPets (const MyPets& myPets) {
std::cout << "My cat: " << myPets.catAge << " years old, " << myPets.catWeight << " pounds, "
<< myPets.catColour << "." << std::endl;
std::cout << "My dog: " << myPets.dogAge << " years old, " << myPets.dogWeight << " pounds, "
<< myPets.dogColour << ", will bite = " << myPets.dogWillBite << "." << std::endl;
std::cout << "My bird: " << myPets.birdName << ", " << myPets.birdColour <<
", can fly = " << myPets.birdCanFly << std::endl;
}
int main() {
std::cout.setf (std::ios_base::boolalpha);
listOutMyPets ({
{Cat, 8, 10.4, Black},
{Dog, 6, 12.5, Brown, true},
{Bird, Yellow, true, "Polly"}
});
std::cin.get();
}
|