0

I've got a couple of header/source files: FUNCS.h and FUNCS.cpp, MATRIX.h and MATRIX.cpp, and main.cpp . In funcs and my MATRIX class there should be complex library, but when I try to include it in my MATRIX.h for example, I get error that complex is not a template. Where should I include the library so all my headers would define complex as a template? Example:

#pragma once
#include <complex>
class MATRIX
{
    friend MATRIX sum(MATRIX a, MATRIX b);
    friend MATRIX mult(MATRIX a, MATRIX b);
    friend MATRIX vi4(MATRIX a, MATRIX b);
    friend MATRIX operator * (const MATRIX& a, complex<int> b);
    friend MATRIX operator * (complex<int> b, const MATRIX& a);

private:
    complex<int>** M;
    int m;
    int n;

public:
    MATRIX();
    MATRIX(int _m, int _n);
    MATRIX(int _m);
    MATRIX(const MATRIX& _M);
    complex<int> get(int i, int j);
    void set(int i, int j, complex<int> value);
    void Print();
    MATRIX operator=(const MATRIX& _M);
    complex<int>* operator[] (int index);
    ~MATRIX();
};

2 Answers2

2

What is defined in <complex> is std::complex, what you are trying to use is complex, and the compiler cannot find something called complex in the global scope.


Change

friend MATRIX operator * (complex<int> b, const MATRIX& a);

to

friend MATRIX operator * (std::complex<int> b, const MATRIX& a);

Or introduce the name via

using std::complex;

but don't do that in a header! Rather put that in the source file only. The reason to not do it in a header is that all other code that includes the header will "inherit" it and it will lead to problems on the long run.


The header you should include in every file that uses std::complex.

Note that sometimes you can get away with including it indirectly, as in: a.h includes <complex>, b.h includes a.h hence it can use std::complex without expliticly including <complex>. Do not rely on that! It will cause trouble on the long run.

Further note that often a forward declaration is sufficient. It goes beyond what you have in your example, but I mention it for the sake of completeness. You don't need the definition in a header when all you use is pointers and references to a type. A declaration is sufficent in this case and the header can be included in the source only. This can reduce compilation time in huge projects.

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

Where should I include <complex>

In every file where you use the declarations of that file, before those usages. Conventionally, headers are included at the beginning (head) of the file

complex<int>** M;

I get error that complex is not a template.

<complex> doesn't declare ::complex. It declares std::complex. Use std::complex instead.

eerorika
  • 232,697
  • 12
  • 197
  • 326