#include#include #include #include class Pet { private: std::string name_; int age_; std::string type_; std::string id_; public: Pet(std::string name, int age, std::string type) { name_ = name; age_ = age; type_ = type; id_ = GetGUID(); } std::string GetName() { return name_; } int GetAge() { return age_; } std::string GetType() { return type_; } std::string GetID() { return id_; } std::string GetGUID() { char buf[64]; snprintf(buf, sizeof buf, "%02x%02x%02x%02x%02x%02x%02x%02x", rand() % 256, rand() % 256, rand() % 256, rand() % 256, rand() % 256, rand() % 256, rand() % 256, rand() % 256); return std::string(buf); } }; int main() { Pet p1("Fido", 5, "Dog"); Pet p2("Mittens", 3, "Cat"); std::cout << "Pet 1\n"; std::cout << "Name: " << p1.GetName() << std::endl; std::cout << "Age: " << p1.GetAge() << std::endl; std::cout << "Type: " << p1.GetType() << std::endl; std::cout << "ID: " << p1.GetID() << "\n\n"; std::cout << "Pet 2\n"; std::cout << "Name: " << p2.GetName() << std::endl; std::cout << "Age: " << p2.GetAge() << std::endl; std::cout << "Type: " << p2.GetType() << std::endl; std::cout << "ID: " << p2.GetID() << std::endl; return 0; }
#includeIn this example, the Pet class is defined similarly to Example 1, but this time, the boost library is used to generate a unique identifier instead of the rand() function. The boost library provides a random_generator()() function that generates a UUID (universally unique identifier) for the pet object. The UUID is then converted to a string using the to_string() function before being returned by the GetID() function. Package/library: Boost C++ library.#include #include #include #include class Pet { private: std::string name_; int age_; std::string type_; boost::uuids::uuid id_; public: Pet(std::string name, int age, std::string type) { name_ = name; age_ = age; type_ = type; id_ = boost::uuids::random_generator()(); } std::string GetName() { return name_; } int GetAge() { return age_; } std::string GetType() { return type_; } std::string GetID() { return boost::uuids::to_string(id_); } }; int main() { Pet p1("Fido", 5, "Dog"); Pet p2("Mittens", 3, "Cat"); std::cout << "Pet 1\n"; std::cout << "Name: " << p1.GetName() << std::endl; std::cout << "Age: " << p1.GetAge() << std::endl; std::cout << "Type: " << p1.GetType() << std::endl; std::cout << "ID: " << p1.GetID() << "\n\n"; std::cout << "Pet 2\n"; std::cout << "Name: " << p2.GetName() << std::endl; std::cout << "Age: " << p2.GetAge() << std::endl; std::cout << "Type: " << p2.GetType() << std::endl; std::cout << "ID: " << p2.GetID() << std::endl; return 0; }