我正在对类和构造函数进行实验,并尝试根据if语句之类的内容为类对象选择特定的声明。我已经写了一个简单的例子来说明我想要做的事情,但这并不起作用。即使它满足if -语句,它也会打印第一个声明的对象的"id“,如果我没有在if语句之前声明它,我会得到打印的错误消息"a not statement 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();
}
发布于 2018-05-06 18:07:22
if-else
块中的a
对象与它们之前的对象不同。它们是在if-else
块中创建和销毁的,不会更改第一个对象。
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
如果要更改第一个对象,请使用assignment。
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
发布于 2018-05-06 20:09:36
是否有重新声明类对象的方法
是。你可以多次声明一个对象。但只定义一次(ODR -唯一定义规则)。
并在之后通过if语句使用它?sic -语法错误
在main中,你有3个重叠的作用域。这是您的代码,我在其中添加了大括号以澄清范围。
int main(int, char**)
{ // scope 1 begin
int i=9;
potato a(i); // scope 1 potato ctor
if(i==3)
{ // scope 2 begin
potato a(5);
a.show(); // of potato in scope 2 (scope 1 potato is hidden)
} // scope 2 end
else
{ // scope 3 begin
potato a(3);
a.show(); // of potato in scope 3 (scope 1 potato is hidden)
} // scope 3 end
a.get_id();
a.show(); // show contents of scope 1
} // scope 1 end
如果不隐藏或遮挡对象,则可以在每个范围内使用范围1土豆:
int main(int, char**)
{ // scope 1 begin
int i=9;
potato a(i); // __scope 1 potato ctor__
if(i==3)
{ // scope 2 begin
// replace "potato a(5);" with
a.modify(5); // __modify scope 1 potato__
a.show(); // __of potato in scope 1__
} // scope 2 end
else
{ // scope 3 begin
// replace "potato a(3);" with
a.modify(3); // __modify scope 1 potato__
a.show(); // __of potato in scope 1__
} // scope 3 end
a.get_id();
a.show(); // show contents of scope 1
} // scope 1 end
在这个版本中,只有一个土豆被ctor'd (和dtor'd)。并且将其修改为基于if子句的值一次。
https://stackoverflow.com/questions/50202896
复制相似问题