Версия для печати темы
Нажмите сюда для просмотра этой темы в оригинальном формате
Форум программистов > Центр помощи > [C++] Задачи на дружественные функиции


Автор: yull 13.3.2012, 13:21
Спасите бедного студента от бессонных ночей((
1. Создать два класса - в первом объявить несколько полей в private секции. Обратиться к этим полям из методов второго класса. Один класс устанавливает значения своих полей, а второй - их читает и выдает на экран.
2. Написать свой класс, реализующий работу с комплексными числами. Создать перегруженный оператор "+" для класса таким образом, чтобы он был объявлен вне класса. (Для этого его необходимо сделать "другом").

Автор: t_gran 15.3.2012, 05:41
yull, почитайте правила форума. На каждую задачу должна быть своя тема.

Первая задача
Код

#include <iostream>

class TPoint
{
   private:
      int x, y;

   public:
      TPoint(): x(0), y(0) { ; }
      TPoint(int theX, int theY): x(theX), y(theY) { ; }

      void Set(int theX, int theY)
      {
         x = theX;
         y = theY;
      }

      friend class TPointReader;
};

class TPointReader
{
   public:
      void Print(const TPoint& thePoint)
      {
         std::cout << "x=" << thePoint.x << " y=" << thePoint.y << std::endl;
      }
};

int main()
{
   TPoint point(3, 4);
   TPointReader reader;
   
   reader.Print(point);

   return 0;
}


Вторая задача
Код

#include <iostream>

class TComplex
{
   private:
      double real;
      double imagine;
      
   public:
      TComplex(): real(0), imagine(0) { ; };

      TComplex(double theReal, double theImagine = 0)
      : real(theReal), imagine(theImagine) { ; };
   
      friend TComplex operator + (const TComplex&, const TComplex&);
      friend std::ostream& operator << (std::ostream&, const TComplex&);
};
//----------------------------------------------//
TComplex operator + (const TComplex& theFirst, const TComplex& theSecond)
{
   TComplex temp;
   temp.real = theFirst.real + theSecond.real;
   temp.imagine = theFirst.imagine + theSecond.imagine;

   return temp;
}
//----------------------------------------------//
std::ostream& operator << (std::ostream& theOut, const TComplex& theNumber)
{
   theOut << '(' << theNumber.real << ',' << theNumber.imagine << ')';

   return theOut;
}
//----------------------------------------------//
int main()
{
   TComplex complex1(3, 4), complex2(1, 7);
   
   std::cout << complex1+complex2 << std::endl;

   return 0;
}

Powered by Invision Power Board (http://www.invisionboard.com)
© Invision Power Services (http://www.invisionpower.com)