提问人:Sharkes Monken 提问时间:5/2/2018 更新时间:5/2/2018 访问量:1222
未找到采用 c++ 类型的左手操作数的运算符
No operator found which takes a left-hand operand of type c++
问:
需要帮助找出以下源代码的问题所在。我有一个类来计算多个字符,并将每个字符显示到控制台屏幕中。
但不幸的是,当我尝试编译时,我一直收到这个错误消息
错误 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);
};
}
字符计数器.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;
}
主 .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赞
Alexey Usachov
5/2/2018
#1
您需要为 , 重载运算符,因为 声明它:>>
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;
}
下一个:gcc:剥离未使用的函数
评论
operator<<
operator>>
CharacterCounter
const
operator <<
>>
main
while (cin >> character)
while (cin >> counter)
fill_n 甚至 std
::memset
来“清除”数组。fCharacterCounts
operator<<
operator>>