返回一个指向数组的指针
假设您有一个带有指向数组的私有指针的类。如何使用 getter 来访问(或有效复制数据),以便可以在不同的变量中访问它。
class MyClass
{
private:
double *x;
public:
myClass();
virtual ~MyClass();
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
}
在这种情况下,bar[0]和bar[1]等于乱码:-9.2559631349317831e+061
。
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();
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
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
它不会构造一个对象,该对象声明一个名为
spam
的函数,该函数不接受任何参数并返回MyClass
。此默认构造一个对象:有关更多信息,请谷歌最令人烦恼的解析。
更新:正如@Mark Ransom 指出的那样,您的代码还存在另一个问题。在构造函数中创建一个数组,然后设置 x 指向该数组。然而,一旦构造函数完成执行,数组的生命周期就结束了,因此进一步访问
x
将会崩溃(如果你足够幸运)。That does not construct an object, that declares a function called
spam
that takes no arguments and returns aMyClass
. This default constructs an 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 tox
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.
那可能应该是 *bar 而不是 bar[0]。
That should probably be *bar instead of bar[0].