Home > Mobile >  Expected class name error, inheritance in C
Expected class name error, inheritance in C

Time:12-24

I have two classes in C - Vector and VectorFile (which inherits from Vector class). While creating VectorFile class I got error: Expected class name, so the compiler can't see Vector class in VectorFile.h, although I have included it.

VectorFile.h:

#include<iostream>
#include "Vector.h"
using namespace std;
class VectorFile : public Vector{
public:
    ostream &operator << (ostream &output, Vector &V);
    istream &operator >> (istream &input, Vector &V);
};

Vector.h:

#include<iostream>
using namespace std;

template<typename type>
class Vector{
protected:
    type *data;
    size_t allocatedDataSize;
    size_t usingDataSize{};
public:
   
    Vector();
    Vector(size_t usingDataSize);
    ~Vector();
};

CodePudding user response:

As your Vector is a template and not a class, you have to give the type for your Vector to make it a class template instance.

class VectorFile : public Vector< put your type here >{

Maybe VectorFile itself will becomes a template if needed:

template < typename T>
class VectorFile : public Vector< T >{

From your comment:

and then defining a variable std::vector v{};. What's missing

The same as before! As your Vector is a template, you have to give the template parameters to get a template instance which is a type itself. You can define variables only from types, not from templates.

std::vector<int> v{};

If you use C 20, the template parameter can automatically deduced from given values to the constructor. As an example, if you provide some values for a std::vector, the template automatically instantiates for that type:

std::vector v{1,2,3};

In this case, you have std::vector<int>

In addition, you can also write user defined deduction guides... but this is the next question :-)

CodePudding user response:

VectorFile inherits from a template class, so it must also be a template class.

template<typename type>
class VectorFile : public Vector<type>{
public:
    ostream &operator << (ostream &output, Vector<type> &V);
    istream &operator >> (istream &input, Vector<type> &V);
};

This code will have another error: "error: ‘std::ostream& VectorFile::operator<<(std::ostream&, Vector&)’ must have exactly one argument". I did not fix this because it's not obvious whether you want to give Vector or VectorFile as the argument.

See this question for instructions how to fix it: operator << must take exactly one argument

  •  Tags:  
  • c
  • Related