C++ Template Class for Comparing Two Values: Max and Min
"template <typename T>\nclass Compare {\npublic:\n // Constructor that initializes num1 and num2 with the given values\n Compare(T a, T b) : num1(a), num2(b) {}\n\n // Returns the maximum value between num1 and num2\n T getMax() {\n return (num1 > num2) ? num1 : num2;\n }\n\n // Returns the minimum value between num1 and num2\n T getMin() {\n return (num1 < num2) ? num1 : num2;\n }\n\nprivate:\n T num1; // First number\n T num2; // Second number\n};\n\nThe code above defines a template class called "Compare". A template class allows you to define a generic class that can work with different data types. In this case, the class is designed to compare two values of the same data type and find the maximum and minimum values.\n\nThe class has two private member variables, "num1" and "num2". These variables store the two values that will be compared.\n\nThe constructor takes two parameters of type T and initializes the member variables with the given values.\n\nThe class has two member functions, "getMax()" and "getMin()". Both functions return a value of type T.\n\nThe "getMax()" function uses a ternary operator to check if num1 is greater than num2. If it is, num1 is returned; otherwise, num2 is returned. This function finds and returns the maximum of the two values.\n\nThe "getMin()" function uses a ternary operator to check if num1 is less than num2. If it is, num1 is returned; otherwise, num2 is returned. This function finds and returns the minimum of the two values.
原文地址: https://www.cveoy.top/t/topic/qd5C 著作权归作者所有。请勿转载和采集!