2016-06-14 5 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; 
} 

:あなたはoperator<<Streamを使用する必要があり、 coutではありません。

+0

おかげさまで、友だちの機能でやりました。今はすべて機能しています。他の方法でも試してみます:)) – specbk

関連する問題