我正在尝试为我的班级使用 operator<<。这是代码:
课堂定义:
friend std::ostream& operator<<(std::ostream& out, const longint& num);
类外定义:
std::ostream& operator<<(std::ostream& out, const longint& num_) {
if (num_.negative())
out << '-';
longint::const_iterator it = num_.array.end();
--it;
longint::const_iterator finish = num_.array.begin();
--finish;
while (it != finish) {
out << num_.digtochar(*it);
--it;
}
}
longint::negative
是公开的,longint::array
也是longint::digtochar
私有的。在很多谷歌搜索的例子中,我可以看到私人成员可以在朋友运算符中使用,但我给出了错误:
../long_arithm.h:57:20: error: «std::list<signed char> long_arithm::longint::array» is private
../long_arithm.cpp:94:36: error: in this context
../long_arithm.h:57:20: error: «std::list<signed char> long_arithm::longint::array» is private
../long_arithm.cpp:96:40: error: in this context
../long_arithm.h:44:9: error: «long_arithm::schar long_arithm::longint::digtochar(long_arithm::schar) const» is protected
../long_arithm.cpp:99:28: error: in this context
为什么?我做错了什么?
UPD。最小代码:
// long_arithm.h
#ifndef LONG_ARITHM_H_
#define LONG_ARITHM_H_
#include <iostream>
#include <list>
namespace long_arithm {
typedef signed char schar;
class longint {
public:
typedef std::list<schar>::const_iterator const_iterator;
inline bool negative() const { return minusSign; }
friend std::ostream& operator<<(std::ostream& out, const longint& num);
enum { error_char = 127 };
protected:
schar digtochar(schar num) const;
private:
bool minusSign;
std::list<schar> array;
};
};
// long_arithm.cpp
#include "long_arithm.h"
#include <iostream>
using namespace long_arithm;
schar longint::digtochar(schar num) const {
switch (num) {
case 0: return '0';
case 1: return '1';
case 2: return '2';
case 3: return '3';
case 4: return '4';
case 5: return '5';
case 6: return '6';
case 7: return '7';
case 8: return '8';
case 9: return '9';
default: return error_char;
}
}
std::ostream& operator<<(std::ostream& out, const longint& num_) {
if (num_.negative())
out << '-';
longint::const_iterator it = num_.array.end();
--it;
longint::const_iterator finish = num_.array.begin();
--finish;
while (it != finish) {
out << num_.digtochar(*it);
--it;
}
return out;
}
谢谢你的回答。