我是 C++ 的新手(来自 Java),实际上我正在为 下列的: 让 foo 成为一个类
int bar[10] = {};
Foo::Foo()
{
bar[1] = 42;
}
和 doSmth() 是主类中的一个方法:
Foo doSmth(){
Foo f;
f.bar[0] = 10;
return f;
}
主要是这样的:
int main(int argc, char *argv[])
{
Foo f = doSmth();
cout << f.bar[1] << endl;
cout << f.bar[0] << endl;
return 0;
}
这是在 doSmth()
中返回 foo
对象的正确方法吗?
我想在堆栈上创建对象,但我担心 foo 对象中的 array (bar)
何时会从堆栈中删除?
最佳答案
Is this the right way to return the foo object in doSmth()?
当然是。
I want to create the object on stack
你有。
but i'm worried about the array (bar) from the foo object
bar
不是“来自 foo
”。 bar
是一个全局静态对象。
f.bar[1]
这是错误的格式,因为 bar
不是 Foo
的成员。要声明一个成员,它必须在类的定义中:
struct Foo {
int bar[10] = {};
};
when will it be deleted from stack?
如果 bar
有静态存储,例如在您的代码中,那么它会在程序结束时被销毁。如果它是一个(非静态)成员,那么当它的完整对象被销毁时它也被销毁,即包含它的 Foo
的实例。
关于c++创建具有数组作为成员的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44394079/