2010-04-24 129 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中創建函數,這樣可以在不公開成員的情況下提供您尋求的功能。