我的问题是关于朋友的功能以及重载<<和>>从我的理解,我认为朋友的功能可以(并且应该)直接访问私有成员变量.但是在我这里的情况下,当我使用“get”函数来获取每个私有变量时,编译器将只接受我的.cxx文件.
这是我的头文件
class BigNum public: // CONSTRUCTORS and DESTRUCTORS BigNum(); BigNum(int num,size_t optional_base = 10); BigNum(const char strin[],size_t optional_base = 10); // MEMBER FUNCTIONS size_t get_digit(size_t index) const; size_t get_used() const; size_t get_capacity() const; size_t get_base() const; bool get_sign() const; // FRIEND FUNCTIONS friend std::ostream& operator<<(std::ostream &os,const BigNum &bignum); friend std::istream& operator>>(std::istream &is,BigNum &bignum); private: size_t base; size_t *digits; bool positive; size_t used;
#include "file.h" #include <cstdlib> #include <iostream> #include <string> #include <cstring> using namespace std; std::ostream& operator <<(std::ostream &os,const BigNum &bignum) { if (bignum.get_sign() == false) os << '-'; for (size_t i = 0; i < bignum.get_used(); ++i) os << bignum.get_digit(bignum.get_used() - i - 1); return os; } std::istream& operator >>(std::istream &is,BigNum &bignum) { for (size_t i = 0; i < bignum.get_used(); ++i) is >> bignum.digits[i]; return is; }
所以在这方面上面的朋友操作符编译正确.但是为什么我的运算符>>可以直接访问一个私有变量(是>> bignum.digits [i]),但是其余的私有变量需要通过’get函数’检索
下面,当我尝试在这方面编写重载操作符(我以为朋友的功能如何正确地调用私有变量):
std::ostream& operator <<(std::ostream &os,const BigNum &bignum) { if (bignum.positive == false) os << '-'; for (size_t i = 0; i < bignum.used; ++i) os << bignum.digits[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; }
我收到以下错误.
BigNum2.cxx: In function `std::ostream& csci2270_hw1B::operator<<(std::ostream&,const csci2270_hw1B::BigNum&)': BigNum2.cxx:201: error: `used' undeclared (first use this function) BigNum2.cxx:201: error: (Each undeclared identifier is reported only once for each function it appears in.) BigNum2.cxx: In function `std::istream& csci2270_hw1B::operator>>(std::istream&,csci2270_hw1B::BigNum&)': BigNum2.cxx:208: error: Syntax error before `)' token
我使用的编译器是g(版本3.3.1).任何帮助不胜感激,谢谢.
修订:
我更新了代码,使得bignum对象可以访问私有变量.我对朋友的运算符进行了以下操作:<<它编译好了.感谢您的意见,那是新秀的错误.
std::ostream& operator <<(std::ostream &os,const BigNum &bignum) { if (bignum.positive == false) os << '-'; for (size_t i = 0; i < bignum.used; ++i) os << bignum.digits[bignum.used - i - 1]; return os; }
但是,编译器仍然会产生>>操作者
BigNum2.cxx:在函数std :: istream&
csci2270_hw1B :: operator>>(std :: istream& csci2270_hw1B :: BigNum&)’:
BigNum2.cxx:208:错误:之前的语法错误)’标记
>>应该读取一个数字,私有成员变量’used’应该记录数组的长度.我仍然对编译器接受的原因感到困惑
std::istream& operator >>(std::istream &is,BigNum &bignum) { for (size_t i = 0; i < bignum.get_used()); ++i) is >> bignum.digits[i]; return is; }
而不是:
std::istream& operator >>(std::istream &is,BigNum &bignum) { for (size_t i = 0; i < bignum.used); ++i) is >> bignum.digits[i]; return is; }
有什么想法吗?谢谢.