Code Fix

初級

error: no match for 'operator>>' の原因と直し方

std::cout に >> を使ったり、std::cin に << を使ったりと、ストリーム演算子の向きを取り違えたときに出るエラーです。<<は出力(送り込む)、>>は入力(受け取る)で向きが逆です。

エラーメッセージの読み方

main.cpp:4:15: error: no match for 'operator>>' (operand types are 'std::ostream' {aka 'std::basic_ostream<char>'} and 'int')
main.cpp
ファイル名
4
行番号
15
列番号 — この位置でg++が構文解析に失敗しました
no match for 'operator>>' (operand types are 'std::ostream' {aka 'std::basic_ostream<char>'} and 'int')
内容 — 期待していたもの、または受け付けられなかったもの

このエラーが出る典型パターン

パターン1

 1  #include <iostream>
 2  int main() {
 3      int score = 90;
 4      std::cout >> score;
                   ^
 5      return 0;
 6  }
main.cpp:4:15: error: no match for 'operator>>' (operand types are 'std::ostream' {aka 'std::basic_ostream<char>'} and 'int')

std::coutは出力用のストリームで、値を送り込む向きの<<しか受け付けません。>>は入力用のstd::cinのための演算子です。

直し方: >><< にします。

この問題を解いてみる →

広告
広告スロット(未設定)

パターン2

 1  #include <iostream>
 2  int main() {
 3      std::cout >> "result: " << 42 << std::endl;
                   ^
 4      return 0;
 5  }
main.cpp:3:15: error: no match for 'operator>>' (operand types are 'std::ostream' {aka 'std::basic_ostream<char>'} and 'const char [9]')

coutの直後に置く演算子はすべて<<でなければなりません。1箇所でも>>にすると、そこでストリーム演算子の連鎖が壊れます。

直し方: >><< にします。

この問題を解いてみる →

パターン3

 1  #include <iostream>
 2  int main() {
 3      int age;
 4      std::cin << age;
                  ^
 5      std::cout << age << std::endl;
 6      return 0;
 7  }
main.cpp:4:14: error: no match for 'operator<<' (operand types are 'std::istream' {aka 'std::basic_istream<char>'} and 'int')

std::cinは入力用のストリームで、値を受け取る向きの>>しか受け付けません。<<はstd::coutのための演算子です。

直し方: <<>> にします。

この問題を解いてみる →

よくある誤解

「矢印の向きさえ合っていれば矢印の種類は気にしなくていい」と誤解されがちですが、<<と>>はそれぞれcoutとcinという別の型に対して別々に定義された演算子です。向きを間違えるとそもそも対応する演算子が存在しません。

まとめ

error: no match for 'operator>>'は初級でつまずきやすい項目です。上の3パターンを実際に手で直すと、エラーメッセージのどこを読めばよいかが掴めます。

演習をはじめる

関連するエラー

広告
広告スロット(未設定)