asmodeus94

przeciazanieOperatorow

Apr 19th, 2016
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.87 KB | None | 0 0
  1. // k5.cpp : Defines the entry point for the console application.
  2. //
  3.  
  4. #include "stdafx.h"
  5. #include <iostream>
  6. #include <conio.h>
  7. #include <ctime>
  8.  
  9. using namespace std;
  10.  
  11. class B {
  12.     int wartosc;
  13. public:
  14.     void set(int);
  15.     int& get();
  16. };
  17.  
  18. class A {
  19.     B *b;
  20.     int rozmiar;
  21. public:
  22.     A(int = 5);
  23.     const int getRozmiar();
  24.     friend ostream& operator<<(ostream&, const A&);
  25.     friend istream& operator>>(istream &in, A &prawy);
  26.     int& operator[](int);
  27.     int& operator()(int);
  28.     A& operator=(A&);
  29.     A* operator->();
  30. };
  31.  
  32. A::A(int r)
  33. {
  34.     rozmiar = r;
  35.     b = new B[rozmiar];
  36.     for (int i = 0; i < rozmiar; i++)
  37.     {
  38.         b[i].set(rand() % (9) + 1);
  39.     }
  40. }
  41.  
  42. const int A::getRozmiar()
  43. {
  44.     return rozmiar;
  45. }
  46.  
  47. void B::set(int w)
  48. {
  49.     wartosc = w;
  50. }
  51.  
  52. int& B::get()
  53. {
  54.     return wartosc;
  55. }
  56.  
  57. int& A::operator[](int index)
  58. {
  59.     return b[index].get();
  60. }
  61.  
  62. int& A::operator()(int index)
  63. {
  64.     return b[rozmiar - index - 1].get();
  65. }
  66.  
  67. A& A::operator=(A &prawy)
  68. {
  69.     int max = rozmiar > prawy.rozmiar ? prawy.rozmiar : rozmiar;
  70.     for (int i = 0; i < max; i++)
  71.     {
  72.         b[i].set(prawy.b[i].get());
  73.     }
  74.     return *this;
  75. }
  76.  
  77. A* A::operator->()
  78. {
  79.     return this;
  80. }
  81.  
  82. ostream& operator<<(ostream &out, const A &prawy)
  83. {
  84.     for (int i = 0; i < prawy.rozmiar; i++)
  85.     {
  86.         out << prawy.b[i].get() << (i != prawy.rozmiar - 1 ? ", " : "");
  87.     }
  88.     return out;
  89. }
  90.  
  91. istream& operator>>(istream &in, A &prawy)
  92. {
  93.     cout << "Podaj " << prawy.rozmiar << " wartosci" << endl;
  94.     int w;
  95.     for (int i = 0; i < prawy.rozmiar; i++)
  96.     {
  97.         in >> w;
  98.         prawy.b[i].set(w);
  99.     }
  100.     return in;
  101. }
  102.  
  103. int _tmain(int argc, _TCHAR* argv[])
  104. {
  105.     srand(time(NULL));
  106.     A a, b;
  107.    
  108.     cout << a << endl;
  109.     cin >> a;
  110.     cout << a << endl;
  111.     a[1] = 50;
  112.     cout << "a[1] = " << a[1] << endl;
  113.     cout << a << endl;
  114.     cout << "Rozmiar tablicy obiektu b wynosi: " << (b = a)->getRozmiar() << endl;
  115.     cout << "obiekt b: " << b;
  116.     _getch();
  117.     return 0;
  118. }
Advertisement
Add Comment
Please, Sign In to add comment