I have been implementing a custom Vector from one of the latest C++ books and I am coming upon an error in the vector.cpp and vector.h file at the Class Vector and Vector::Vector respectively: Redefinition of 'Vector'
Here is the code for each file:
main.cpp:
#include <iostream>
#include "Vector.h"
#include "Container.h"
int main(int argc, const char * argv[]) {
return 0;
}
vector.h
class Vector {
public:
Vector(int s) :elem{new double[s]}, sz{s} // constructor: acquire resources
{
for (int i=0; i!=s; ++i) // initialize elements
elem[i]=0;
}
~Vector() { delete[] elem; } // destructor: release resources
double& operator[](int i);
int size() const;
private:
double* elem; // elem points to an array of sz doubles
int sz;
};
vector.cpp
Vector::Vector(int s) // definition of the constructor
:elem{new double[s]}, sz{s} // initialize members
{}
double& Vector::operator[](int i) // definition of subscripting
{
return elem[i];
}
int Vector::size() const // definition of size()
{
return sz;
}
container.cpp
class Container {
public:
virtual double& operator[](int) = 0; // pure virtual function
virtual int size() const = 0; // const member function (§4.2.1)
virtual ~Container() {} // destructor (§4.2.2)
};
class Vector_container : public Container { // Vector_container implements Container
public:
Vector_container(int s) : v(s) { } // Vector of s elements
~Vector_container() {}
double& operator[](int i) override { return v[i]; }
int size() const override { return v.size(); }
private:
Vector v;
};
I tried enclosing the .h file with #ifndef Vector_h,#define Vector_h, and #endif but it the error still appears in Vector_cpp. If I encapsulate Vector.cpp with #ifndef Vector_cpp, #define Vector_h, and #endif the error still appears.
To add insult to injury, when I add Vector.h to container.cpp it tells me: Unknown type name 'Vector' at the bottom where I declared Vector v
Can anyone help me with this?
#ifndef
's for sure, in each header file. Where is yourContainer.h
? – ChrisMMVector::Vector(int s)
constructor in both the header and the .cpp file. Choose one. If your choice is the .cpp file, then strip the body and member initialization list ofVector(int s
)` from the header, leaving only the decl in the header; just like you did with thesize()
member. – WhozCraig