16th week hands-on practice project 3-max conflicts, 16th week max
Analyze the compilation errors of the following programs and provide a solution.
# Include <iostream> using namespace std; // define the function template <class T> T max (T a, T B) {return (a> B )? A: B;} int main () {int x = 2, y = 6; double x1 = 9.123, y1 = 12.6543; cout <"instantiate T as int: "<max (x, y) <endl; cout <" instantiate T as double: "<max (x1, y1) <endl; return 0 ;}
In fact, C ++ has a standard max function. After more than a year of study, we know this. codeblocks will provide a supplement each time we play max, this is clearly defined, so there are several solutions
1. Adding std: before max indicates using max in the standard library
# Include <iostream> using namespace std; // define the function template <class T> T max (T a, T B) {return (a> B )? A: B;} int main () {int x = 2, y = 6; double x1 = 9.123, y1 = 12.6543; cout <"instantiate T as int: "<std: max (x, y) <endl; cout <" instantiate T as double: "<std: max (x1, y1) <endl; return 0 ;}
2. Add: before max to indicate that the currently defined max is used.
# Include <iostream> using namespace std; // define the function template <class T> T max (T a, T B) {return (a> B )? A: B;} int main () {int x = 2, y = 6; double x1 = 9.123, y1 = 12.6543; cout <"instantiate T as int: "<: max (x, y) <endl; cout <" instantiate T as double: "<: max (x1, y1) <endl; return 0 ;}
3. Change using namespace std to using std: cout; using std: endl, which means that only cout and endl in the standard library are used.
# Include <iostream> using std: cout; using std: endl; // define the function template <class T> T max (T a, T B) {return (a> B )? A: B;} int main () {int x = 2, y = 6; double x1 = 9.123, y1 = 12.6543; cout <"instantiate T as int: "<max (x, y) <endl; cout <" instantiate T as double: "<max (x1, y1) <endl; return 0 ;}