有没有办法重新声明一个类对象
是的。您可以多次声明一个对象。但只定义一次(ODR - 单一定义规则)。
然后通过 if 语句使用它?[原文如此-语法错误]
“范围内”的对象可以“使用”。
任何超出范围的对象都不能。
基本上,您有 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
在这个版本中,只有 1 个土豆是 ctor'd(和 dtor'd)。并且根据 if 子句将其修改一次为一个值。