【问题标题】:Operator<< Overloading, endl leads to segmentation fault [closed]运算符<<重载,endl导致分段错误[关闭]
【发布时间】:2013-09-19 13:40:55
【问题描述】:

刚刚将我的程序从 windows 移到了 linux,当从 main 调用 operator<< endl 时它会崩溃,如果我从 main() 中删除 endl 它不会崩溃?

..///main


VecXd<int> x;                                           
        cout << "Input vector a\n"; 

cin >> a;


cout << "Test A: "<< a << endl; //seg fault, -> 
cout << "Test A: " << a; //works

//----- class VecXd\\ opertor<< def + operator>>

  /******************************************************/
   friend istream &operator>>(istream &input, VecXd& vec)
   {

         for(int i = -1; i <= vec.dimension - 1; i++)
         {
           if(i == -1)
           {
           input >> vec.dimension;//>> (V vecArr = new V[vec.dimension]);
           cout << vec.dimension << " dimension check" << endl;
           vec.vecArr = new V[vec.dimension];
                                //vec.dimension = vecArr[0];
                                //cout << vec.dimension << " dimension check" << endl;
           }
           else
           {
           input >> vec.vecArr[i];//>> (V vecArr = new V[vec.dimension]);
           cout << vec.vecArr[i] << " value check" << endl;
           }
         }


   }

   friend ostream& operator<<(ostream& output, const VecXd& vec)
   {
          for(int i = 0; i < vec.dimension; i++)
          {
          output << vec.vecArr[i] << " ";

          }
          output << endl;
         // output << endl;

   }
   /****************************************************/

为什么 endl 会导致崩溃?数组结束输出endl不解决这个问题吗?

【问题讨论】:

  • 问题不清楚。崩溃很可能不是因为使用了endl,检查vec.vecArr 是否是一个有效的指针,i 是否对所有输入都是正确的。

标签: c++ overloading operator-keyword


【解决方案1】:

您忘记返回ostream&amp;(和istream&amp;)。

如果您使用 gcc/clang/icc,请在编译命令中添加 -Wall 标志

【讨论】:

  • 糟糕,进行了意外编辑。请忽略。实际评论:我想知道 OPs 编译器是否对此发出警告...
  • 就是这样!感谢 Anycom!
  • 默认情况下 gcc 不会警告丢失返回。我有时会被这个咬伤。
  • @SxMZ np man,我偶尔会犯同样的错误。 -Wall 非常有助于发现这样的错误。
猜你喜欢
  • 1970-01-01
  • 2013-03-25
  • 2013-11-21
  • 1970-01-01
  • 2014-11-30
  • 2013-08-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多