SOLVED, C++ Returning a pointer or reference to an array data member
Hello, just a little question.
I have an object, Character, that has an array of ints as a data member. Let's say it's called:
int m_myArray[9];
I want to write a method for this object that returns a pointer or reference to myArray so that another object, called Actor, can receive it and access the values in the array.
The method in Character may look something like this:
int ArrayQuery() { return m_myArray[0]; } ;
The Actor object needs to call Character.ArrayQuery() to find out the address of the array and store it in a data member so that it can access elements in the array from any of its methods.
So Character has an array of ints as a data member, and Actor has access to this array (a reference or pointer?) stored as a data member. The end result is, any method of Actor can access the
values in the Character object's m_myArray[].
The Actor object will know the size of the array, so I don't need to worry about bounds checking.
Should I pass as a pointer or reference and perhaps someone can help with the syntax?
[Edited by - darenking on August 2, 2005 4:42:17 AM]
If I understand your question correctly then the simplest possible thing would be:
class Character{public: const int* GimmieTheArray(void) const { return myArray;}private:int myArray[ArraySize];};
Quote:Original post by DigitalDelusionclass Character{public: const int* GimmieTheArray(void) const { return myArray;}private:int myArray[ArraySize];};
Pointer decay is a nasty thingTM [grin]:
struct Character { typedef const int (&const_array_ref)[30]; typedef int (&array_ref)[30];private: int myArray[30];public: const_array_ref GimmieTheArray() const { return myArray; }};
Quote:Original post by Basiror
you could simply overload the operator <type you want to return>*(){return yourarray};
User-defined implicit conversions can be much, much more sinisterTM. Another generally bad practice unless completely necessary which nearly all of the time is not the case.
[Edited by - snk_kid on July 20, 2005 8:48:54 AM]
Quote:Original post by snk_kid
Pointer decay is a nasty thingTM [grin]:
DontRepeatYourself[attention]
class Character{ typedef int array_t[ArraySize]; typedef array_t& array_ref; typedef array_t const& const_array_ref;public: const_array_ref GimmieTheArray(void) const { return myArray;}private: array_t myArray;};
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement