c++ friend function - operator overloading istream >>

≯℡__Kan透↙ 提交于 2019-11-29 06:09:36

A friend function has access to the class' private data, but it does not get a this pointer to make that automatic, so every access to the class' data (private or otherwise) has to be qualified. For example this:

os << bignum.digits[used - i - 1];

needs to be:

os << bignum.digits[bignum.used - i - 1];
In silico

You haven't qualified used in the first function - it needs to be bignum.used. The operator overloads are defined at global scope, so they don't get a this pointer. However, the friend functions do have access to the private members of the class.

std::ostream& operator <<(std::ostream &os, const BigNum &bignum) 
{ 
    if (bignum.positive == false) 
        os << '-'; 

    for (size_t i = 0; i < bignum.used; ++i) 
        // Note "bignum.used", instead of "used".
        os << bignum.digits[bignum.used - i - 1];     
    return os; 
} 

std::istream& operator >>(std::istream &is, BigNum &bignum) 
{ 
    for (size_t i = 0; i < bignum.used; ++i) 
        is >> bignum.digits[i]; 

    return is; 
} 

It seems there is an extra ')' in the following line right after bignum.used.

 for (size_t i = 0; i < bignum.used**)**; ++i)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!