Main Function Error C++
I have this main function:
#ifndef MAIN_CPP
#define MAIN_CPP
#include "dsets.h"
using namespace std;
int main(){
DisjointSets s;
s.uptree.addelements(4);
for(int i=0; i<s.uptree.size(); i++)
cout <<uptree.at(i) << endl;
return 0;
}
#endif
And the following class:
class DisjointSets
{
public:
void addelements(int x);
int find(int x);
void setunion(int x, int y);
private:
vector<int> uptree;
};
#endif
My implementation is this:
void DisjointSets::addelements(int x){
for(int i=0; i<x; i++)
uptree.push_back(-1);
}
//Given an int this function finds the root associated with that node.
int DisjointSets::find(int x){
//need path compression
if(uptree.at(x) < 0)
return x;
else
return find(uptree.at(x));
}
//This function reorders the uptree in order to represent the union of two
//subtrees
void DisjointSets::setunion(int x, int y){
}
Upon compiling main.cpp (g++ main.cpp)
I'm getting these errors:
dsets.h: In function \u2018int main()\u2019: dsets.h:25: error: \u2018std::vector > DisjointSets::uptree\u2019 is private
main.cpp:9: error: within this context
main.cpp:9: error: \u2018class std::vector >\u2019 has no member named \u2018addeleme开发者_Go百科nts\u2019
dsets.h:25: error: \u2018std::vector > DisjointSets::uptree\u2019 is private
main.cpp:10: error: within this context
main.cpp:11: error: \u2018uptree\u2019 was not declared in this scope
I'm not sure exactly whats wrong. Any help would be appreciated.
You can't access a private element of a class from outside the class. Try making uptree public, or provide a means to access it through DisjointSets. Also, addelements() is a member of class DisjointSets, not vector uptree.
#ifndef MAIN_CPP
#define MAIN_CPP
#include "dsets.h"
using namespace std;
int main(){
DisjointSets s;
s.uptree.addelements(4); // try s.addelements(4)
for(int i=0; i<s.uptree.size(); i++) // try making uptree public
cout <<uptree.at(i) << endl;
return 0;
}
#endif
uptree
is a private member of DisjointSets
. You could make it public but it's better to create functions in DisjointSets that will provide the functionality you seek without making the members public.
精彩评论