2016-06-14 78 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<<friend

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

或者添加一個成員函數爲其:

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; 
    } 
    ... 
}; 

然後從operator<<調用它:

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

BTW:你應該在operator<<使用Stream,不是cout

+0

謝謝,它與朋友功能,它現在都在工作。我會用另一種方式嘗試它:))) – specbk