Return a pointer to an array
Suppose you have a class with a private pointer to an array. How can you use a getter to access (or effectively copy the data) so you can access it in a different variable.
class MyClass
{
private:
double *x;
public:
myClass();
virtual ~MyClass(开发者_StackOverflow中文版);
double* getX() const;
void setX(double* input);
};
MyClass::MyClass()
{
double foo[2];
double * xInput;
foo[0] = 1;
foo[1] = 2;
xInput = foo;
setX(xInput);
}
void MyClass::setX(double * input)
{
x = input;
}
double * MyClass::getX() const;
{
return x;
}
int main()
{
MyClass spam(); // Construct object
double * bar = spam.getX(); // This doesn't work
}
In this case, bar[0] and bar[1] are equal to jibberish: -9.2559631349317831e+061
.
MyClass spam(); // Construct object
That does not construct an object, that declares a function called spam
that takes no arguments and returns a MyClass
. This default constructs an object:
MyClass spam; // Construct object
For more information google the most vexing parse.
Update: As @Mark Ransom pointed out, there is another problem with your code. In your constructor you create an array, and then set x
to point to such array. However the array lifetime ends once the constructor finishes execution, so further access to x
would crash (if you are lucky enough).
Just a guess, the program is crashing or showing the wrong output. This is because the constructor is setting a pointer to a local array, which leaves scope and gets destroyed at the end of the constructor.
That should probably be *bar instead of bar[0].
精彩评论