I am in the middle of a c++ project and I get the well-known error "not declared in this scope". Specifically "vexp was not declared in this scope". As you can see below, vexp is a vector declared in class Exploration and although I have included Exploration.h in main, vexp is not reachable. On the other hand Exploration::vexp is not acceptable because vexp is not static. Is making vexp static the only way to access it from main???
#include "exploration.h"
#include <iostream>
#include <vector>
int main()
{
std::srand (time(NULL));
for(int i=1; i<9; i++)
{
Exploration temp (0,3,3);
vexp.push_back(temp);
}
for(int j=0; j<(int)Exploration::vexp.size(); j++)
{
std::cout << Exploration::vexp[j].Vertical;
std::cout << Exploration::vexp[j].Horizontal;
std::cout << Exploration::vexp[j].r;
std::cout << '\n';
}
return 0;
}
And the header:
#ifndef EXPLORATION_H
#define EXPLORATION_H
#include<vehicle.h>
#include <vector>
class Exploration : public vehicle
{
public:
std::vector <Exploration> vexp;
Exploration(bool,float,int);
int r;
void DangerCheck();
bool expaxis(int k);
};
#endif // EXPLORATION_H
vexp
is a non-static member of Exploration
. Each Exploration
object you create will have its own vexp
member. So to access a vexp
, you need to have an Exploration
object. That is, the following would work:
Exploration exp1(false, 3.0f, 5);
Exploration exp2(true, 6.0f, 10);
exp1.vexp.push_back(exp2);
Note that I'm accessing the vexp
member of exp1
with exp1.vexp
. That is the vector that belongs to that particular Exploration
object. To that vector I am pushing exp2
.
What exactly you need to do depends on what you're trying to do, and that I am not sure of. It seems that you don't fully grasp object-oriented principles. It should be clear to you that because vexp
is a non-static member of Exploration
, it doesn't exist until you create an Exploration
object. That is, each Exploration
object owns a container of more Exploration
objects.
It looks as though maybe you just want a std::vector<Exploration>
that is not a member of Exploration
. So you just want a container of Exploration
s, not owned by other Exploration
s. For that, you would just do:
int main()
{
std::srand (time(NULL));
std::vector<Exploration> vexp; // vexp has been moved here
for(int i=1; i<9; i++)
{
Exploration temp (0,3,3);
vexp.push_back(temp);
}
for(int j=0; j < vexp.size(); j++)
{
std::cout << vexp[j].Vertical;
std::cout << vexp[j].Horizontal;
std::cout << vexp[j].r;
std::cout << '\n';
}
}
Note that vexp
is now declared local to the main
function and should be removed from the Exploration
class.