2010-04-24 125 views
1

我有这个主要功能:主要功能错误C++

#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 

及以下等级:

class DisjointSets 
    { 
public: 
void addelements(int x); 
int find(int x); 
void setunion(int x, int y); 

private: 
vector<int> uptree; 

}; 

#endif 

我的实现是这样的:

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){ 

} 

在编译main.cpp中( g ++ main.cpp)

我得到廷这些错误:

dsets.h:在功能\ u2018int主()\ u2019: dsets.h:25:错误:\ u2018std ::矢量> DisjointSets :: uptree \ u2019是私人

主的.cpp:9:错误:在这一范围内

main.cpp中:9:错误:\ u2018class的std ::矢量> \ u2019没有名为\ u2018addelements \ u2019

dsets.h部件:25:错误:\ u2018std :: vector> DisjointSets :: uptree \ u2019是私人的

main.c PP:10:错误:在这一范围内

的main.cpp:11:错误:\ u2018uptree \ u2019并没有在此范围内

宣布我不知道究竟什么是错。 任何帮助,将不胜感激。

+3

您可能希望接受一些答案。 – WhirlWind 2010-04-24 03:38:00

+4

对于任何.cpp文件,不需要包含警卫(代码中的MAIN_CPP)。 – 2010-04-24 04:17:44

回答

2

您无法从课程外部访问某个类的私有元素。尝试向上公开,或提供通过DisjointSets访问它的方法。另外,addelements()是类DisjointSets的成员,而不是向上的树。

#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 
1

uptreeDisjointSets的私人成员。您可以将其公开,但最好在DisjointSets中创建函数,这样可以在不公开成员的情况下提供您寻求的功能。