Tuesday, July 14, 2009

C++; Ampersand trouble!?

I have a function in a class, that is the type of another class. This "Example%26amp;" is in a class called "Answer."





Example%26amp; example() const;








I'm getting this error, as I try to return the instance of Example:


error C2440: 'return' : cannot convert from 'const Example' to 'Example %26amp;'.





What the heck does this mean, and how can I fix it so it will return properly? The function should be able to let the Answer class access the functions in Example. My instance is called myExample.





PLEASE HELP! (I've tried everything..)

C++; Ampersand trouble!?
so you have something like:





class Answer {


...


Example%26amp; example() const;


...


}





the problem is that you have marked the example function as const - which means that it can't modify the Answer object, and everything that it deals with is considered const too.


When you want to return some Example object that is part of Answer, you give away the permission to modify this Example, thus modifying the Answer object itself.





The solution would be to change the function to:


const Example%26amp; example() const;


(then you'll return a const reference to the Example which you won't be able to modify from outside)





or to:


Example%26amp; example();


(declare example as non-const, so it can do everything with Answer)





or even:


Example example() const;


(here you return a copy of the original Example object, so you it the original value can't be modified from outside)
Reply:%26amp; (Ampersand) is used to determine the actual address of the function. I've not yet encountered any function with an (%26amp;) before its header name. Try to use * (Asterisk) instead of this... If you rather want to use pointers... (^^,)





http://ronaldborla.blogsome.com/


No comments:

Post a Comment