How to create one class inside the other in C++?

Asked

Viewed 664 times

1

I need to create one class inside the other in C++

For example: I already have the Calculator class created. I need to insert the Operator class within it. How should I create it? How will the header file look . h and the source . cpp?

Someone to give me strength?

Thanks!

  • Why do you need?

  • The problem statement is this: So we will create a new class called Operator which will be part of the Calculator class. Similarly, a new part class, called Trigonometric Operator may be added to the Calculator class to perform the future sine, cosene and tangent calculation operations. Therefore the whole class Calculator will have two part objects: the object of type Operator and the object of type Operadortrigonometric.

  • For what is there is not to create a class within another. And actually the statement calls for something that doesn’t seem to be adequate, I don’t know the text is a little strange to say. Without a specific context I would say it is not to do so.

1 answer

1

Just use class within the class. Note that the visibility applies the class variable equal to any other method. In the example below the class OperadorAritmetico is private.

// Calculadora HPP

class Calculadora {
  class OperadorAritmetico {
   public:
    int soma(int a, int b);
  };

  OperadorAritmetico operador;

 public:
  int soma(int a, int b);
};

At the source do not forget to put the complete method path.

// Calculadora.cpp
#include <iostream>
#include "Calculadora.hpp"

int Calculadora::OperadorAritmetico::soma( int a, int b )
{
  return a+b;
}

int Calculadora::soma( int a, int b )
{
  return operador.soma( a, b );
}

In this simple test the method soma of Calculadora calls internally the method soma of OperadorAritmético.

int main( void )
{
  Calculadora calc;
  std::cout << "3 + 5 = " << calc.soma( 3, 5 ) << std::endl;
}
  • Thanks for the help!! After looking more calmly in the booklet posted by prof, I ended up finding what I wanted, which was to make strong or weak composition, as below: a) Strong and weak composition in the private area: class A { private: B b; // Strong C *pc; // Weak public: ;};

Browser other questions tagged

You are not signed in. Login or sign up in order to post.