我正在对类和构造函数进行实验,并且尝试根据 if 语句之类的内容为类对象选择特定的声明。我写了一个简单的例子来展示我尝试做的事情,但这是行不通的。即使它满足 if 语句,它也会打印第一个声明的对象的“id”,如果我不在 if 语句之前声明它,我会收到打印错误“a not statements in this scope”。有没有办法重新声明一个类对象并随后通过 if 语句使用它?
class potato{
private:
int id;
public:
void get_id(){
cout<<id<<endl;
}
potato(int x){
id=x;
}
};
int main(){
int i=9;
potato a(i);
if(i==3){
potato a(5);
}
else
potato a(3);
a.get_id();
}
最佳答案
if-else
block 中的 a
对象与之前的对象不同。它们在 if-else
block 中创建和销毁,并且不会更改第一个对象。
potato a(i); // Object 1
if(i==3){
potato a(5); // Object 2.
}
else
potato a(3); // Object 3
a.get_id(); // Still object 1
如果要更改第一个对象,请使用赋值。
potato a(i); // Object 1
if(i==3){
a = potato(5); // Changes object 1.
}
else
a = potato(3); // Changes object 1.
a.get_id(); // Should have new value
关于c++ - 如何在C++中重新声明类对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50202896/