2016-06-14 80 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