如何使用插入和提取运算符重载C ++中的对象

时间:2019-03-20 12:22:57

标签: c++ operator-overloading extraction insertion

在代码的某些部分中,类被定义为Meal。该类Meal有一个名为total的对象,我想显示并接受total属性的输入。我有很多解决方案,但没有得到适当的解决方案。请帮助我解决这个问题。我将不胜感激。

void operator <<(ostream &out, Meal &ob)
    {
        out<<"Entree: "<<ob.entree<<endl;
        out<<"Calorie: "<<ob.countCalorie<<endl;
    }
    void operator >>(istream &input, Meal &ob)
    {
        cout<<"Enter entree: ";
        input>>ob.entree;
        cout<<"Enter calorie: ";
        input>>ob.countCalorie;
    }


int main()
{
Meal *week[21], total;
string entree;
int cal;
for(int i = 0; i < 21; i++)
{
    cout<<"Enter "<<i+1<<" entree: ";
    cin>>entree;
    cout<<"Enter "<<i+1<<" calorie: ";
    cin>>cal;

    week[i] = new Meal(entree,cal);
}
for(int i = 0; i < 21 ; i++)
{
    total = total + week[i];
}
cout<<total;

cin>>total;

}

0 个答案:

没有答案