2016-06-14 3 views
0

다음 코드에 대한 질문이 있습니다. 그 아이디어는 "< <"및 ">>"연산자를 사용하여 다른 값을 입력하고 인쇄하는 것입니다. 내 질문은 - anzahlzahlen 회원을 비공개로 공개하지 않도록하려면 어떻게해야합니까? 방금 비공개로 입력하면 클래스 외부의 메서드에 사용할 수 없습니다. 더 나아질 수 있도록 코드에서 수정할 수있는 것이 있습니까?일반 회원을 비공개로 변경

#include <iostream> 
#include <cmath> 

using namespace std; 

class Liste{ 

public: 
int anzahl; 
int * zahlen; 
Liste(){ 
cout <<"Objekt List is ready" << endl; 
anzahl = 0; 
} 
~Liste(){ 
cout <<"Objekt destroyed" << endl; 
delete (zahlen); 
} 
void neue_zahlen(int zahl){ 

if(zahl == 0){ return;} 

if(anzahl == 0){ 

    zahlen = new int[anzahl+1]; 
    zahlen[anzahl] = zahl; 
    anzahl++; 
    } 
    else{ 

    int * neue_zahl = new int[anzahl+1]; 
     for(int i = 0; i < anzahl; i++){ 
      neue_zahl[i] = zahlen[i]; 
     } 
    neue_zahl[anzahl] = zahl; 
    anzahl++; 

    delete(zahlen); 
    zahlen = neue_zahl; 
    } 

    } 
    }; 






// Liste ausgeben 

ostream& operator<<(ostream& Stream, const Liste &list) 
{ 
cout << '['; 
    for(int i=0; i < list.anzahl; i++){ 

      cout << list.zahlen[i]; 
    if (i > (list.anzahl-2) { 
     cout << ','; 
    } 
     } 
    cout << ']' << endl; 

return Stream; 
} 


//Operator Liste einlesen 

istream& operator>>(istream&, tBruch&){ 

cout<< 

} 




int main(){ 

Liste liste; //Konstruktor wird aufgerufen 
int zahl; 
cout <<"enter the numbers" << endl; 
do{ 
     cin >> zahl; 
     liste.neue_zahlen(zahl); 

    }while(zahl); 


    cout<<liste; 

    } 

답변

0

비회원 기능으로는 개인 회원이 액세스 할 수 없습니다. 다음 operator<<에서 호출

class Liste{ 
    public: 
    void print(ostream& Stream) const { 
     Stream << '['; 
     for (int i=0; i < list.anzahl; i++) { 
      Stream << list.zahlen[i]; 
      if (i > (list.anzahl-2) { 
       Stream << ','; 
      } 
     } 
     Stream << ']' << endl; 
    } 
    ... 
}; 

을 :

ostream& operator<<(ostream& Stream, const Liste &list) 
{ 
    list.print(Stream); 
    return Stream; 
} 

을 BTW :

class Liste{ 
    friend ostream& operator<<(ostream& Stream, const Liste &list); 
    ... 
}; 

또는 그것을 위해 멤버 함수를 추가 : 당신은 operator<<friend을 만들 수 있습니다 당신은 operator<<Stream를 사용한다, 아닙니다 cout.

+0

감사합니다. 친구 기능을 사용 했으므로 이제는 모두 작동합니다. 나는 다른 방법으로 그것을 시도 할 것이다 :)) – specbk