-1

This is a simple example.

EXAMPLE 1 If for example I declare this code (with class Complejo in same file):

#include <iostream>
#include <string>

using namespace std;

int main()
{
  Complejo com(1,1);

  cout << com << endl;

}


class Complejo
{
private:
  double real;
  double imaginario;
public:
  //Complejo();
  Complejo(double real, double imaginario)
  {
    real = 1;
    imaginario = 2;
  }
  double getReal() { return real; }
  double getImaginario() { return imaginario; }
};

ostream &operator<<(ostream &stream, Complejo& comp)
{
  stream << comp.getReal() << " + " << comp.getReal()<< endl;
  return stream;
}

My compiler says me:

sobrecarga_ostream.cpp:15:3: error: unknown type name 'Complejo'

EXAMPLE 2 But If I create sobrecarga_ostream.cpp:

#include <iostream>
#include <string>
#include "Complejo.h"
using namespace std;

int main()
{    
  Complejo com(1,1);


  cout << com << endl;

}

and Complejo.h:

#include <iostream>

using namespace std;

class Complejo
{
private:
  double real;
  double imaginario;
public:
  //Complejo();
  Complejo(double real, double imaginario)
  {
    real = 1;
    imaginario = 2;
  }
  double getReal() { return real; }
  double getImaginario() { return imaginario; }
};

ostream &operator<<(ostream &stream, Complejo& comp)
{
  stream << comp.getReal() << " + " << comp.getReal()<< endl;
  return stream;
}

Then, it works well.

Why does not "main + class" work in the same file and if I separate files then works?

Thanks!

ProgrammerJr
  • 107
  • 6

2 Answers2

4

You cannot use the type before it is declared. If you rearrange your first example to

using namespace std;

class Complejo {
    //...
};

int main()
{
  Complejo com(1,1);

  cout << com << endl;

}

It will complie. Note that #include does nothing more than including the contents of the header into the source file. So your example 2 is more or less the same as the above.

PS: Please read why is using namespace std considered bad practice.

463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185
2

Why does not "main + class" work in the same file

Because when the compiler sees the line

Complejo com(1,1);

in your main functions, it needs to have seen the definition of type Complejo beforehand. There is no way around it - whether you put it into a header file and include that or whether you cut and paste the class definition from below the main function on top of it doesn't matter, both approaches work.

lubgr
  • 37,368
  • 3
  • 66
  • 117