《C++ primer plus》课后习题11.7,求解。

类定义部分

 #include <iostream>

using namespace std;

class plural
{
    private:
        double A;
        double B;
    public:
        plural();
        plural(double ,double);
        ~plural();
        plural operator+(plural CB);
        plural operator-(plural CB);
        plural operator*(plural CB);
        friend plural operator*(double x,plural CA);
        friend plural operator~(plural CA);
        friend ostream & operator<<(ostream &os,plural CA);
        friend bool operator>>(istream &is,plural &CA);
};

plural::plural()
{
    A=0.0;
    B=0.0;
}

plural::plural(double A_,double B_)
{
    A=A_;
    B=B_;
}

plural::~plural()
{

}

plural plural::operator+(plural CB)
{
    plural CC;
    CC.A=A+CB.A;
    CC.B=B+CB.B;
    return CC;
}

plural plural::operator-(plural CB)
{
    plural CC;
    CC.A=A-CB.A;
    CC.B=B-CB.B;
    return CC;
}

plural plural::operator*(plural CB)
{
    plural CC;
    CC.A=A*CB.A-B*CB.B;
    CC.B=A*CB.B+B*CB.B;
    return CC;
}

plural operator*(double x,plural CA)
{
    plural CB;
    CB.A=x*CA.A;
    CB.B=x*CA.B;
    return CB;
}

plural operator~(plural CA)
{
    plural CC;
    CC.A=CA.A;
    CC.B=-CA.B;
    return CC;
}

ostream & operator<<(ostream &os,plural CA)
{
    os<<CA.A<<'+'<<CA.B<<'i';
    return os;
}

bool operator>>(istream &is,plural &CA)
{
    char ch;
    cin.get(ch);
    if(ch!='q')
    {
        cout<<"real:";
        is>>CA.A;
        cout<<endl<<"imaginary:";
        is>>CA.B;
        return true;
    }
    else
        return false;


}

主函数部分

 #include "11.7_func.cpp"

int main()
{
    plural AA(3.0,4.0);
    plural CC;
    cout<<"enter a plural number (q to quit)"<<endl;
        while(cin>>CC)
        {
        cout<<" CC is "<<CC<<endl;
        cout<<"complex conjugate is "<<~CC<<endl;
        cout<<"a is "<<AA<<endl;
        cout<<"a+c is "<<AA+CC<<endl;
        cout<<"a-c is "<<AA-CC<<endl;
        cout<<"a*c is "<<AA*CC<<endl;
        cout<<"2*c is "<<2*CC<<endl;
        cout<<"enter a plural number (q to quit)"<<endl;
        }
    cout<<"done!"<<endl;
    return 0;
}

运行出现的问题是,无论输入什么字符,q或者不是q,这个循环体都只执行一次。
我觉得是

 bool operator>>(istream &is,plural &CA)
{
    char ch;
    cin.get(ch);
    if(ch!='q')
    {
        cout<<"real:";
        is>>CA.A;
        cout<<endl<<"imaginary:";
        is>>CA.B;
        return true;
    }
    else
        return false;


}

出了问题,但是又看不出问题在哪?求大神解答。

1个回答

感觉。。没问题啊。。

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!