C++ 对象生命范围
C++ object life scope
我似乎误解了c++中对象的生命范围。如果您考虑以下几点:
class MyClass{
public:
int classValue;
MyClass(int value){
classValue = value;
}
static MyClass getMyClass(int value){
MyClass m1 = MyClass(value);
return m1;
}
};
int main() {
MyClass m1 = MyClass(3);
cout << m1.classValue << endl;
m1 = MyClass::getMyClass(4);
cout << m1.classValue << endl;
return 0;
}
这输出:
3
4
而且我认为,当 m1 获得一个非动态对象时,该对象已创建 'on the stack' getMyClass 函数,我试图从中获取值是行不通的,因为该对象将是死的。有人可以启发我吗?不要给我任何细节!
And I thought, that when m1 gets a non-dynamic object, that has been created 'on the stack' of getMyClass function, me trying to get a value from it wouldn't work, because the object would be dead. Could someone enlighten me? Do not spare me any details!
有点误会
是的,对象是在getMyClass
中的堆栈上创建的。
是的,当函数 returns.
时对象已死
但是,行:
m1 = MyClass::getMyClass(4);
在对象死亡前将函数的return值赋值给m1
。该对象的寿命足以让 运行 时间完成分配。
顺便说一句,行
MyClass m1;
不对,因为 MyClass
没有默认构造函数。您可以替换行
MyClass m1;
m1.value = 3;
仅靠一个班轮
MyClass m1(3);
更新
您需要更改 MyClass
的构造函数。
MyClass(int value){
value = value; // This does not initialize the
// member variable of the class.
// The argument shadows the member variable.
}
使用:
MyClass(int valueIn) : value(valueIn) {}
我似乎误解了c++中对象的生命范围。如果您考虑以下几点:
class MyClass{
public:
int classValue;
MyClass(int value){
classValue = value;
}
static MyClass getMyClass(int value){
MyClass m1 = MyClass(value);
return m1;
}
};
int main() {
MyClass m1 = MyClass(3);
cout << m1.classValue << endl;
m1 = MyClass::getMyClass(4);
cout << m1.classValue << endl;
return 0;
}
这输出:
3
4
而且我认为,当 m1 获得一个非动态对象时,该对象已创建 'on the stack' getMyClass 函数,我试图从中获取值是行不通的,因为该对象将是死的。有人可以启发我吗?不要给我任何细节!
And I thought, that when m1 gets a non-dynamic object, that has been created 'on the stack' of getMyClass function, me trying to get a value from it wouldn't work, because the object would be dead. Could someone enlighten me? Do not spare me any details!
有点误会
是的,对象是在getMyClass
中的堆栈上创建的。
是的,当函数 returns.
但是,行:
m1 = MyClass::getMyClass(4);
在对象死亡前将函数的return值赋值给m1
。该对象的寿命足以让 运行 时间完成分配。
顺便说一句,行
MyClass m1;
不对,因为 MyClass
没有默认构造函数。您可以替换行
MyClass m1;
m1.value = 3;
仅靠一个班轮
MyClass m1(3);
更新
您需要更改 MyClass
的构造函数。
MyClass(int value){
value = value; // This does not initialize the
// member variable of the class.
// The argument shadows the member variable.
}
使用:
MyClass(int valueIn) : value(valueIn) {}