需要帮助找出以下源代码的问题。我有一个单独的类来计算一些字符并将它们中的每一个显示到控制台屏幕中。
但不幸的是,当我尝试编译
时,我不断收到此错误消息错误C2678:二进制'>>' :找不到哪个运算符带有'std :: istream'类型的左手操作数(或者没有可接受的转换)
以下是源文件:
CharacterCounter.h
#include <iostream>
class CharacterCounter {
public:
int fTotalNumberOfCharacters;
int fCharacterCounts[256]; // hold all 256 byte values
public:
CharacterCounter();
void count(unsigned char aCharacter);
friend std::ostream& operator<<(std::ostream& aOStream, CharacterCounter& aCharacterCounter);
};
}
CharacterCounter.cpp
#include "CharacterCounter.h"
#include <iostream>
/// Constructor
CharacterCounter::CharacterCounter() {
fTotalNumberOfCharacters = 0;
for (int i=0; i < 256; i++) {
fCharacterCounts[i] = i;
}
}
/// Counts the corresponding data member
void CharacterCounter::count(unsigned char aCharacter) {
fTotalNumberOfCharacters++;
fCharacterCounts[aCharacter]++;
}
/// Output stream displays characters greater than 0
std::ostream& operator<<(std::ostream& aOStream, const CharacterCounter& aCharacterCounter) {
for (int i=0; i < 256; i++) {
if (aCharacterCounter.fCharacterCounts[i] > 0) {
int character = aCharacterCounter.fCharacterCounts[i];
aOStream << (unsigned char)i << ":\t" << character << "\n";
}
}
return aOStream;
}
Main.cpp的
#include <iostream>
#include <string>
#include "CharacterCounter.h"
using namespace std;
int main() {
CharacterCounter counter;
unsigned char character;
while (cin >> counter) { **Compilation error focuses here**
counter.count(character);
}
cout << counter;
system("pause");
return 0;
};
答案 0 :(得分:0)
您需要为>>
重载运算符CharacterCounter
,因为cin >> counter
,声明它:
class CharacterCounter {
public:
//...
friend std::istream& operator>>(std::istream& input, CharacterCounter& aCharacterCounter);
//...
然后声明函数重载:
std::istream &operator>>( std::istream &input, CharacterCounter& aCharacterCounter )
{
input >> aCharacterCounter. fTotalNumberOfCharacters;
// Or input something else or more
return input;
}