Our Blog

Пример работы с классами и наследованием

Для демонстрации примера работы с классами и наследованием решим задачу: Создать базовый класс Pair (пара целых чисел) с операциями проверки на равенство и перемножения полей. Реализовать операцию вычитания пар по формуле (a, b)-(c, d)=(a-b, c-d). Создать производный класс Rational; определить новые операции сложения (a, b)+(c, d)=(ad+bc, bd) и деления (a, b)/(c, d)=(ad, bc), переопределить операцию вычитания (a, b)-(c,d)=(ad-bc, bd).

Pair.h:
	
		
	#pragma once
	#include <iostream>
	class Pair {
	public:
	Pair(void);
	Pair (int, int);
	~Pair(void);
	bool isequal ();
	int multiply ();
	friend Pair operator- (const Pair&, const Pair&);
	friend std::ostream& operator<< (std::ostream& out, Pair& p);
	int a, b;
	};
	
		
	class Rational : public Pair {
	public:
	friend Rational operator+ (const Rational&, const Rational&);
	friend Rational operator/ (const Rational&, const Rational&);
	friend Rational operator- (const Rational&, const Rational&);
	Rational (int, int);
	
		
	};
	
		
	
		
	
		
	Pair.cpp:
	#include "stdafx.h"
	#include "Pair.h"
	
		
	
		
	Pair::Pair(int a, int b) {
	this->a=a;
	this->b=b;
	}
	
		
	Pair::Pair (void) {
	a=0;
	b=0;
	}
	
		
	Pair::~Pair(void) {
	}
	
		
	std::ostream& operator<< (std::ostream& out, Pair& p) {
	out << "("<<p.a<<", "<<p.b<<")";
	return out;
	}
	
		
	bool Pair::isequal () {
	return (a==b);
	}
	
		
	int Pair::multiply () {
	return a*b;
	}
	
		
	Pair operator- (const Pair& q1, const Pair& q2) {
	return Pair (q1.a-q1.b, q2.a-q2.b);
	}
	
		
	Rational::Rational (int a, int b) {
	this->a=a;
	this->b=b;
	}
	
		
	Rational operator+ (const Rational& q1, const Rational& q2) {
	return Rational (q1.a*q2.b+q1.b*q2.a, q1.b*q2.b);
	}
	
		
	Rational operator/ (const Rational& q1, const Rational& q2) {
	return Rational (q1.a*q2.b, q1.b*q2.a);
	}
	
		
	Rational operator- (const Rational& q1, const Rational& q2) {
	return Rational (q1.a*q2.b-q1.b*q2.a, q1.b*q2.b);
	}
	
		
	exam.cpp:
	
		
	#include "stdafx.h"
	#include <iostream>
	#include "Pair.h"
	
		
	int main () {
	setlocale(LC_ALL,"Russian");
	Pair q (10, 9);
	if (q.isequal()) std::cout << "Числа равны\n";
	else std::cout << "Числа не равны\n";
	std::cout << "Произведение полей равно " << q.multiply ();
	std::cout <<"\n";
	Pair q1 (10, 4);
	Pair q2 (5, 1);
	Pair q3=q1-q2;
	std::cout << q3<<"\n";
	
		
	Rational w1 (4, 1);
	Rational w2 (5, 5);
	Rational w3=w1-w2;
	std::cout << "Разность пар "<< w1 << " и "<<w2<<" равно "<<"\n";
	std::cout << w3<<"\n";
	Rational e1 (8, 1);
	Rational e2 (3, 4);
	std::cout << "Сумма пар "<< e1 << " и "<<e2<<" равно "<<"\n";
	Rational e3=e1+e2;
	std::cout << e3<<"\n";
	Rational r1 (9, 0);
	Rational r2 (3, 3);
	std::cout << "Частное пар "<< r1 << " и "<<r2<<" равно "<<"\n";
	Pair r3=r1/r2;
	std::cout << r3<<"\n";
	return 0;
	}
Comments ( 0 )
    -->