开发者

Variable was not declared in this scope?

I'm getting this error in several methods for several variables (all of which are vectors):

error: ‘parent’ was not declared in this scope

I've tried wrapping my method implementations inside of "namespace DisjointSubsets { ... }", but that causes other problems. It seems to only do this for vectors, and I've tried adding a "#include vector" at the start of the cpp file, it didn't change anything.

Here is the header file:

#ifndef UNIVERSE 
#define UNIVERSE 
#include <vector>
class DisjointSubsets { 
    public :
        DisjointSubsets ( unsigned numberElements = 5 ) ;
        unsigned findDS ( unsigned ) ;
        bool uni开发者_高级运维onDS ( unsigned , unsigned ) ;
    private :
        vector<unsigned> parent ;
        vector<unsigned> rank ;
        unsigned size ;
} ;
#include "DisjointSubsets.cpp"
#endif

And here is an example of one of the methods I wrote in the cpp file (which has no #includes):

unsigned DisjointSubsets::findDS(unsigned index) {
    return parent[index];
}

(Changed the method to be non-functional, but still illustrate the kind of line that would cause a problem. Just in case someone else working on the assignment stumbles across this.)


You must use std::vector<unsigned> instead of just vector<unsigned> to declare parent because vectoris declared in the std namespace. Therefore you could also use using namespace std; before declaring the class.

However most people I know would discourage you from using the second form in a header file. See the C++ FAQ for a more elaborate discussion on this topic.


vector is in the std namespace. Use std::vector or put a using namespace std; after your #includes.


You cannot include .cpp files like this and expect it to work. That code is compiled independently, as well as as a part of other translation units. When you attempt to compile, that C++ code is compiled- but you didn't include the declaration. Unless the class is a template, the .cpp should include the .h, not the other way around.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜