1
我正在嘗試爲我的課程使用操作符< <。 下面的代碼:使用朋友操作符的編譯器錯誤<<
定義類:
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;
}
謝謝你的回答。
它應該工作。發佈複製問題的最小代碼。 – 2012-04-22 17:20:25
你應該從你的函數返回'out'。 – chris 2012-04-22 17:20:46
@LuchianGrigore行,發佈。 – 2012-04-22 17:29:31