C ++ question ... the definition does not recognize vectors specified in the declaration

I'm working on a class assignment that started small, so I had everything in one file. Now it's gotten bigger and I'm trying to compile the main, functions and classes separately (so all the classes are combined into one .h and one .cpp). I have one class B which is the parent of many others and comes first in the file. One of its data members is not working now that I am using a separate compilation that throws dozens of errors.

In .h

class A;
class B {
public: 
    B (){}
    A* myptr;
    void whatever();
    vector<A*> myAs; //this one is the problem
};

      

In .cpp

void B::whatever() {
    vector<A*> newvector; //no problem!
    myptr = &something; //no problem!
    for (vector<A*>::iterator iter = myAs.begin(); iter != myAs.end(); ++iter) {
        //error!
    }
}

      

I get errors: either "myAs was not declared in this scope" or "class B does not have a myAs member".

I've included the <vector>, forward-declared class A as you see above, and I definitely remember to include .h at the top of the .cpp! Is there something about vectors or classes and separate compilation that I don't understand? It's in Xcode, BTW.

0


a source to share


1 answer


It's not easy vector

. It std::vector

is because it is in a namespace called std

. This is why the compiler groans. He doesn't know what he means vector<A*>

. Tell me std::vector<A*>

.



Don't add using namespace std;

to the title now because of this. It might be OK for assignment to put it in a .cpp file to save text input if you like. But it's really a bad idea to put a line like this in your header: because you don't know what files your header will need in the future. This can quickly get out of hand as the number of files, including your header, grows over time. The header should only contain the names and headers that it really needs so that it causes as few naming conflicts as possible, while the string using namespace std;

would display all names std

directly.

+4


a source







All Articles