简体   繁体   中英

Make a pointer on an object that has a reference member?

I'm a student beginner in C++ (but yet have few hours on C), and I'm actually having a problem to use a pointer on my object. I really tried to find infos on the web, but it was pointless (pointless-pointer, do you get it ?!). So I try my luck here.

This code compiles now ! My apologies to all of you that try the code before that. Compiled with :

g++ -Wall -o exec main.cc

 #include <iostream>
 #include <vector>

 //all the includes here
 using namespace std;

 class ExpLog
 {
 public: 
   virtual string toString() const=0;
   //virtual int evaluate() const=0;
 };


 class Atom : public ExpLog
 {    
 protected:
   int value;

 public:
   Atom():value(0){}
   string toString() const
   {
     return "a";//definition doesn't matter here
   } 

 };


 class ExpNot : public ExpLog
 {    
 protected:
   const ExpLog& opd; 

 public:
   ExpNot(const Atom& a):opd(a){}
   string toString() const
   {
     return "NOT"+opd.toString();
   }

 };

 const ExpLog *my_function(vector<Atom> const& vect_atom, int i)
 {
   if(i>= vect_atom.size()) return NULL;

   const Atom *a =  &vect_atom[i]       ;

   if(i>0) 
     return a;
   else{
     ExpNot *n;
     n = new ExpNot(*a);
     cout<<n->toString()<<endl; //This line leads to a seg:fault
     return n;         

   }
 }


 int main()
 {
   int i=-2;
   vector<Atom> vect_atom(3);

   my_function(vect_atom, i);
 }

As others have said, this code snippet(s) does not compile in its current form. However, I'm willing to guess the problem is not in the line you have indicated, but the line

const Atom *a =  &vect_atom[i]       

If i > vect_atom.size() then this will point outside of the vector. Try adding a check for this just like you have a check for i < 0 . If that check does match, then search up the for the root cause: the caller that is passing an invalid index.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM