Tuesday, July 28, 2009

Please I want to connect two pointers and it is not working. i am programming in c++ with dev compiler.help me

/*i want to connect frisk pointer and blackee pointer please help me.thanks*/





#include %26lt;iostream%26gt;


using namespace std;


class Cat


{


public:


int GetAge();


void SetAge (int age);


void Meow();


Cat *blackee;


private:


int itsAge;


};


int Cat::GetAge()


{


return itsAge;


}


void Cat::SetAge(int age)


{


itsAge = age;


}


void Cat::Meow()


{


cout %26lt;%26lt; "Meow.\n";


}


int main()


{


Cat *Frisky;


Cat *blackee;


blackee-%26gt;SetAge(4);


Frisky-%26gt;blackee;





cout %26lt;%26lt; "Frisky is a cat who is " ;


cout %26lt;%26lt; Frisky/*.GetAge()*/ %26lt;%26lt; " years old.\n";


return 0;


}

Please I want to connect two pointers and it is not working. i am programming in c++ with dev compiler.help me
OK First of all you need to understand the difference between a pointer and an instance of a class.





Please read the references and they should explain to you why


blackee-%26gt;SetAge(4) is causing your program to crash and how to fix it.





Namely you need to create instances of Cat not just pointers to them. As for connecting them the pointers tutorial should help you out with that.
Reply:Its been a while since I have written in C, but I think there are 3 things I see:








(1) You need to allocate the memory for blackee based on your code here.





ie: Cat *blackee = new Cat();








(2) The second is on the assignment of Frisky to blackee, it should just be:





Friskey = blackee;








(3) Although it is commented out, you appear to be using the '.' operator for accessing the GetAge() method on Frisky. This should be the -%26gt; operator (because you are accessing the method on the pointer to the object). If you were accessing it on the object (ie: Cat Friskey;), then you could use the '.'.








In this instance, the code would have 2 pointers to the same Cat object. I am not sure if you need both objects (may if the assignment asks for it perhaps), but you could get away with the followibng code instead:





int main()


{


Cat *Friskey = new Cat();


Friskey -%26gt; SetAge(4);





cout %26lt;%26lt; "Friskey is " %26lt;%26lt; Friskey-%26gt;GetAge() %26lt;%26lt; " years old.\n";





return 0;


}








Although it might be interesting for you to do the following:





int main()


{


Cat *Friskey = new Cat();


Cat *blackee;





blackee = Friskey;





Friskey -%26gt; SetAge(4);





// both should be the same age.


cout %26lt;%26lt; "Friskey is " %26lt;%26lt; Friskey-%26gt;GetAge() %26lt;%26lt; " years old.\n";


cout %26lt;%26lt; "Friskey is " %26lt;%26lt; blackee-%26gt;GetAge() %26lt;%26lt; " years old (via blackee pointer).\n";





return 0;


}


No comments:

Post a Comment