将成员从公共更改为私有

Change members from public to private

本文关键字:成员      更新时间:2023-10-16

我对以下代码有疑问。它的想法是使用"<<"和">>"运算符输入和打印不同的值。我的问题是 - 我怎样才能使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;
   }

私有成员不能由非成员函数访问。你可以做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