Operator<< Overloading, endl leads to segmentation fault [closed]

不打扰是莪最后的温柔 提交于 2019-12-25 05:35:31

问题


Just moved my program over from windows to linux and the same code that worked now gives me a segmentation fault when calling the operator<< function from main. (overview) My programs is a Vector class that takes input and returns what the input is, but when reach << endl it crashes, if I remove endl from main() it does not crash?

..///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;

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

why does endl lead to crash? doesn't end of array outputing endl solve this issue?


回答1:


You forget to return ostream& (and istream&).

Add -Wall flag to your compile command if you are using gcc/clang/icc



来源:https://stackoverflow.com/questions/18896294/operator-overloading-endl-leads-to-segmentation-fault

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!