2

我正在对类和构造函数进行试验,并且我正在尝试根据 if 语句之类的内容为类对象选择特定的声明。我写了一个简单的例子,展示了我试图做的事情,但这是行不通的。即使它满足 if 语句,它也会打印第一个声明对象的“id”,如果我没有在 if 语句之前声明它,我会得到错误“a not declared 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();


}
4

2 回答 2

2

块中的对象与它们之前的a对象不同。if-else它们在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

如果要更改第一个对象,请使用赋值。

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-06T18:07:22.150 回答
0

有没有办法重新声明一个类对象

是的。您可以多次声明一个对象。但只定义一次(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 子句将其修改一次为一个值。

于 2018-05-06T20:09:35.500 回答