当我尝试重载运算符时出现分段错误<< for char

问题描述 投票:0回答:1

当我尝试重载运算符时<< for char and use it which

std::cout
出了点问题。在编译期间我没有任何错误,但是当我输入
./a.out
时我看到了
Segmentation fault (core dumped)

这是代码:

  1 #include <iostream>
  2 
  3 std::ostream& operator<<(std::ostream& COUT, char letter)
  4 {
  5   COUT << letter;
  6   return COUT;
  7 }
  8 
  9 int main(void)
 10 {
 11    std::cout << 'l';
 12 }

感谢您的每一次帮助。

c++ segmentation-fault operator-overloading operator-keyword
1个回答
0
投票

问题在于声明

COUT << letter;

将调用您自己的重载函数,导致无限递归。

您需要显式调用“正常”重载函数:

std::operator<<(COUT, letter);
© www.soinside.com 2019 - 2024. All rights reserved.