Task: Create a class of integers Integer. Determine the overloaded function that returns the maximum of two arguments. The function is not a member of the class of integers. Overloaded functions have arguments of type int, double, Integer. The body of overloaded functions should be the same.

I wrote the code, it works. But I doubt that I correctly implemented the overload of friendly functions. Did I do the right thing?

#include "stdafx.h" #include <iostream> #include <conio.h> using namespace std; class Integer { private: double a, b; public: Integer(); ~Integer(); void input(); void output(); friend int max(int a, double b); friend int max(int a, double b, Integer c); }; Integer::Integer() { a = 0; b = 0; cout << "Constructor works" << endl; } Integer::~Integer() { cout << "Destructor works" << endl; a = NULL; b = NULL; } void Integer::input() { cout << "Input two elements: " << endl;; cin >> a >> b; } void Integer::output() { cout << "The largest number is " << max(a,b)<<endl; } int max(int a, double b) { if (a > b) { cout << "The first number is larger than the second" << endl; return a; } else { cout << "The second number is larger than the first" << endl; return b; } } int max(int a, double b, Integer c) { if (a > b) { cout << "The first number is larger than the second" << endl; return a; } else { cout << "The second number is larger than the first" << endl; return b; } } int main() { Integer c; char p='y'; while (p=='y'||p=='Y') { c.input(); c.output(); cout << "Want to continue? y/n" << endl; p = _getch(); } return 0; } 

    1 answer 1

    Do you think this is -

     class Integer { private: double a, b; 

    class declaration for WHOLE numbers?

    As I understand it, you are required to create a class in which the integer value is stored. Type

     class Integer { private: int a; public: Integer(int i); ... int value() const; // Прочий функционал 

    After that, all you need is to write

     int maximum(int a, int b) { return (a>b) ? a : b; } int maximum(double a, double b) { return (a>b) ? a : b; } Integer maximum(const Integer& a, const Integer& b) { return Integer(maximum(a.value(),b.value())); } 

    Somewhere ...

    • Thank. Is it possible in more detail with the function int value () const? - hope_op
    • Well, it just returns the value stored in the class. In the simplest case - this is the most a , which is declared in the class .. - Harry
    • But what does the body of this function look like? - hope_op
    • ??? I wrote - returns the value stored in the class . Excuse me ... this code, what did you write at the beginning of the question? - Harry