Operator<< Overloading, endl leads to segmen

2019-09-08 15:36发布

问题:

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