未找到采用 c++ 类型的左手操作数的运算符

No operator found which takes a left-hand operand of type c++

提问人:Sharkes Monken 提问时间:5/2/2018 更新时间:5/2/2018 访问量:1222

问:

需要帮助找出以下源代码的问题所在。我有一个类来计算多个字符,并将每个字符显示到控制台屏幕中。

但不幸的是,当我尝试编译时,我一直收到这个错误消息

错误 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;
   };
C 可视化-C++ IOstream

评论

2赞 Some programmer dude 5/2/2018
你有 ,不是 .operator<<operator>>
1赞 David G 5/2/2018
的参数应为 。CharacterCounterconst
4赞 Angew is no longer proud of SO 5/2/2018
您正在为类定义(输出),但在 中使用 (input)。你能解释一下为什么你认为这应该有效吗?或者你真的打算写而不是?operator <<>>mainwhile (cin >> character)while (cin >> counter)
0赞 Some programmer dude 5/2/2018
顺便说一句,您的初始化可能不正确。我假设您希望所有元素都为零?使用 std::fill、std::fill_n 甚至 std:memset 来“清除”数组。fCharacterCounts
1赞 Some programmer dude 5/3/2018
如果只想要输出,则仅重载 .如果你只想输入,那么只重载。如果同时想要输出和输入,请同时重载两者。没有规则或“标准”说必须同时实现两者。operator<<operator>>

答:

0赞 Alexey Usachov 5/2/2018 #1

您需要为 , 重载运算符,因为 声明它:>>CharacterCountercin >> 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;            
}