0

Задание: Создать класс целых чисел Integer. Определить перегруженную функцию, воз-вращающую максимальное из двух аргументов. Функция не является членом класса целых чисел. Перегруженные функции имеют аргументы типа int, double, Integer. Тело перегруженных функций должны быть одинаковыми.

Код я написал, он работает. Но сомневаюсь, что правильно реализовал перегрузку дружественных функций. Все ли я правильно сделал?

#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 ответ 1

1

Вы считаете, что это -

class Integer
{
private:
    double a, b;

объявление класса ЦЕЛЫХ чисел?

Как я понимаю, от вас требуется создать класс, в котором хранится целочисленное значение. Типа

class Integer
{
private:
    int a;
public:
    Integer(int i);

    ...

    int value() const;

    // Прочий функционал

После этого все, что вам нужно - это написать

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()));    
}

Где-то так...

4
  • Спасибо. А можно поподробнее с функцией int value() const ?
    – hope_op
    23 дек 2017 в 19:29
  • Ну просто она возвращает хранящееся в классе значение. В простейшем случае - это самое a, которое в классе объявлено..
    – Harry
    23 дек 2017 в 19:32
  • а как выглядит тело этой самой функции?
    – hope_op
    23 дек 2017 в 22:18
  • ??? Я же написал - возвращает хранящееся в классе значение. Простите... этот код, что в начале вопроса - точно вы сами писали?
    – Harry
    24 дек 2017 в 6:12

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.