1

我有这个主要功能:

#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 main()\u2019:dsets.h:25:错误:\u2018std::vector > DisjointSets::uptree\u2019 是私有的

main.cpp:9:错误:在此上下文中

main.cpp:9:错误:\u2018class std::vector >\u2019 没有名为 \u2018addelements\u2019 的成员

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

main.cpp:10:错误:在此上下文中

main.cpp:11:错误:\u2018uptree\u2019 未在此范围内声明

我不确定到底出了什么问题。任何帮助,将不胜感激。

4

2 回答 2

2

您不能从类外部访问类的私有元素。尝试公开 uptree,或者提供一种通过 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
于 2010-04-24T03:31:20.823 回答
1

uptree是 的私人成员DisjointSets。您可以将其公开,但最好在 DisjointSets 中创建函数,以提供您所寻求的功能,而无需公开成员。

于 2010-04-24T03:47:19.803 回答