int *nums
this is later initialized into an array of a certain length. For various reasons, i need to be able to retrieve this raw variable, the array, through a function. Basically what i want to know how to do is make a variable in my main program and through calling the class''s member functions fill this variable out so it''s identical to the nums array. thanks in advance!
getting an array from a class
Hi
I have a class defined that has as one of it''s private members
Make it public
- The trade-off between price and quality does not exist in Japan. Rather, the idea that high quality brings on cost reduction is widely accepted.-- Tajima & Matsubara
class foo{private: int* nums;public: int* GetNums() { return nums; }};int main(){ foo f; int* p; p = f.GetNums();}
[update] Damn! mhkrause beat me by 19 seconds! [/update]
I would say make it public, too. I mean, if you need it outside your class, that's what "public" is for.
But here's what you asked for:
Edited by - Eric on June 26, 2000 10:21:23 PM
I would say make it public, too. I mean, if you need it outside your class, that's what "public" is for.
But here's what you asked for:
class CYourClass {
int* nums;
public:
int* GetPointer(){ return nums; }
};
main(){
CYourClass yc;
// initialize nums into array
int* g_nums = yc.GetPointer();
}
Edited by - Eric on June 26, 2000 10:21:23 PM
Although it''s possible (using the method the guys in the previous posts stated), it goes against the basic rules of OO programming: data hiding and encapsulation. If you''re gonna do it like that, you''d probably better use plain C...
I suggest you do it like this:
Dormeur
I suggest you do it like this:
class foo {private: int* nums;public: foo(int size) { nums = new int [size]; } ~foo() { delete [] nums; } // Returns read-only array const int* GetNums() const { return nums; } // Element manipulation void SetNum(int index, int value) { // Assuming the size of your array is big enough nums[index] = value; } int GetNum(int index) { return nums[index]; } // Or using the [] operator int& operator [] (int index) { return nums[index]; }};int main() { foo f(100); const int* p; p = f.GetNums(); // Using the [] operator f[0] = 100;}
Dormeur
Wout "Dormeur" NeirynckThe Delta Quadrant Development Page
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement
Recommended Tutorials
Advertisement