Ошибка основной функции C ++ - PullRequest
1 голос
/ 24 апреля 2010

У меня есть эта основная функция:

#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: в функции 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 не был объявлен в этой области

Я не уверен, что именно не так. Любая помощь будет оценена.

Ответы [ 2 ]

2 голосов
/ 24 апреля 2010

Вы не можете получить доступ к закрытому элементу класса извне класса. Попробуйте сделать публичный uptree или предоставить доступ к нему через DisjointSets. Кроме того, addelements () является членом класса DisjointSets, а не вектора 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
1 голос
/ 24 апреля 2010

uptree является приватным членом DisjointSets. Вы можете сделать это общедоступным, но лучше создавать функции в DisjointSets, которые будут предоставлять функции, которые вы ищете, не делая членов публичными.

...